import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useAuthStore } from './auth';
import { CollectableModulesNameMapping } from '@/pages/dig/forms/forms';
import VillageApi from '@/api/inhert/VillageApi';

export const useCollectStore = defineStore('collect', () => {
  const collectableModules = ref(new Map<string, number>());
  const authStore = useAuthStore();

  function setCollectableModules(modules: Map<string, number>) {
    collectableModules.value = modules;
  }
  function canCollect(module: string) {
    if (authStore.isAdmin)
      return true;
    if (collectableModules.value.has(CollectableModulesNameMapping[module]))
      return true;
    return collectableModules.value.has(module);
  }
  function getCollectModuleId(module: string) {
    if (collectableModules.value.has(CollectableModulesNameMapping[module]))
      return collectableModules.value.get(CollectableModulesNameMapping[module]);
    return collectableModules.value.get(module);
  }
  function getCollectModuleInternalNameById(id: number) {
    for (const [key, value] of collectableModules.value) {
      if (value == id) {
        for (const k2 in CollectableModulesNameMapping) {
          if (CollectableModulesNameMapping[k2] == key) {
            return k2;
          }
        }
      }
    }
    return '';
  }

  async function loadCollectableModules() {
    const res = await VillageApi.getVolunteerInfo();
    const collectableModules = res.collectModule || [];
    const collectableModulesMap = await VillageApi.getCollectModuleMap();
    const needRemoveKeys = new Set<string>();
    if (!authStore.isAdmin) {
      for (const [key,id] of collectableModulesMap)
        if (!collectableModules.includes(key))
          needRemoveKeys.add(key);
    }
    for (const key of needRemoveKeys)
      collectableModulesMap.delete(key);
    setCollectableModules(collectableModulesMap);
  }
  
  const isEmpty = computed(() => collectableModules.value.size === 0);

  return { 
    isEmpty,
    collectableModules,
    setCollectableModules,
    getCollectModuleInternalNameById,
    getCollectModuleId,
    canCollect,
    loadCollectableModules,
  }
})
