import { GetterTree, MutationTree, ActionTree } from 'vuex';

interface GroupListI {
  name: string
  num: number
  label: string
  hideLabel: boolean
  attrList: string[]
}

interface AttrListI {
  name: string
  label: string
  type: string
  view: string
  hidden: boolean
  readOnly: boolean
}

type SchemaT = {
  id: string
  modified: string
  schema: 'Form'
  name: string
  groupList: GroupListI[]
  attrList: AttrListI[]
}

export const state = {
  forms: {} as Record<string, SchemaT>,
};

export type State = typeof state;

export const mutations: MutationTree<State> = {
  setIndex(state, [name, schema]: [string, SchemaT]) {
    state.forms[name] = schema;
  }
}

export const actions: ActionTree<State, State> = {
  async loadSchemas({ commit, state }, formNames: Record<string, string>): Promise<Record<string, SchemaT>> {
    const modules = await Promise.all(
      Object.entries(formNames).map(async ([name, schemaName]): Promise<[string, SchemaT]> => {
        let schema: SchemaT;
        if (!!state.forms[schemaName]) {
          schema = state.forms[schemaName];
        } else {
          const { default: def } = await import(`@/constants/forms/${schemaName}.json`);
          schema = def;
          commit('setIndex', [schemaName, schema]);
        }
        return [name, schema];
      }
    ));
    const modulesObj = Object.fromEntries(modules);
    return modulesObj;
  },

  async loadSchema({ commit, state }, schemaName: string): Promise<SchemaT> {
    let schema: SchemaT;
    if (!!state.forms[schemaName]) {
      schema = state.forms[schemaName];
    } else {
      const { default: def } = await import(`@/constants/forms/${schemaName}.json`);
      schema = def;
      commit('setIndex', [schemaName, schema]);
    }
    return schema;
  }
}
