import { Module } from 'vuex-module-decorators';
import storeInstance from '@/store';
import { Store } from 'vuex';
import options from './.localmodules';

const { paths, key = 'vuex', storage } = options;

export interface IOptions {
  namespaced?: boolean;
  name: string;
  dynamic?: true;
  store?: Store<any>;
  preserveState?: boolean;
}

function DynamicModule({ namespaced = true, dynamic = true, name, store = storeInstance, preserveState }: IOptions) {
  if (preserveState === undefined) {
    const modulesStr = storage.getItem(key);
    if (paths.includes(name) && modulesStr != null) {
      const modules = JSON.parse(modulesStr);
      preserveState = modules[name];
    } else {
      preserveState = false;
    }
  }
  return Module({
    namespaced,
    dynamic,
    name,
    store,
    preserveState,
  });
}

export default DynamicModule;
