import VillageApi, { VolunteerInfo } from "@/api/inhert/VillageApi";
import { useSimpleDataLoader } from "@/components/composeabe/loader/SimpleDataLoader";
import { useAuthStore } from "@/store/auth";
import { useVillageStore } from "@/store/village";
import { ref } from "vue";

export function useUserTools() {

  const authStore = useAuthStore();
  const villageStore = useVillageStore();
  const volunteerInfo = ref<VolunteerInfo | null>(null);

  async function getIsVolunteer() {
    if (!authStore.isLogged) {
      return false;
    }
    try {
      volunteerInfo.value = await VillageApi.getVolunteerInfo();
      return volunteerInfo.value !== null;
    } catch (e) {
      console.error(e);
      return false;
    }
  }
  async function getIsJoinedVillage(villageId: number) {
    if (!authStore.isLogged) {
      return false;
    }
    if (villageStore.myJoinedVillages.length === 0) {
      await villageStore.loadMyJoinedVillages();
    }
    try {
      const isJoined = villageStore.myJoinedVillages.some(p => p.villageId === villageId) ?? false;
      return isJoined;
    } catch (error) {
      return false;
    }
  }
  async function getCanCollect(villageId: number) {
    if (!authStore.isLogged) {
      return false;
    }
    if (villageStore.myJoinedVillages.length === 0) {
      await villageStore.loadMyJoinedVillages();
    }
    try {
      const village = villageStore.myJoinedVillages.find(p => p.villageId === villageId);
      return Boolean(village !== undefined && village.collectFlag);
    } catch (error) {
      return false;
    }
  }

  return {
    getIsVolunteer,
    getIsJoinedVillage,
    getCanCollect,
    volunteerInfo,
  };
}