import type { Namespace } from "~/classes/Namespace"
import { getNamespaces } from "~/requests/namespace"

export const useNamespaceStore = defineStore('namespace', {
  state: () => ({ 
    namespaces: undefined as Namespace[] | undefined,
    currentNamespace: undefined as Namespace | undefined
  }),
  getters: {
    getNamespaces: (state) => {
      return (): Namespace[] | undefined => {
        return state.namespaces;
      }
    },
    getNamespaceNames: (state) => {
      return (includeAll?: boolean): Map<string, string> | undefined => {
        if (state.namespaces)
        {
          const result = new Map<string, string>();
          if (includeAll === true)
          {
            result.set('_all', 'Alle')
          }
          state.namespaces.forEach(namespace => { result.set(namespace.metadata.name, namespace.metadata.name) });
          return result;
        }
        return undefined;
      }
    },
    getCurrentNamespace: (state) => {
      return (): Namespace | undefined => state.currentNamespace;
    }
  },
  actions: {
    init() {
      getNamespaces((namespaces: Namespace[]) => {
        this.namespaces = namespaces;
      });
    },
    selectNamespace(namespace: Namespace | undefined) {
      if(namespace == null)
      {
        this.currentNamespace = undefined;
      }
      else if(this.currentNamespace?.metadata?.name !== namespace?.metadata?.name)
      {
          this.currentNamespace = namespace;
      }
      else
      {
          this.currentNamespace = undefined;
      }
    }
  },
})