import { isArray, mapValues } from 'lodash';
import { StoreLiteModule } from 'src/widgets/useStoreLite';
import { useStore } from 'vuex';

interface Props {
  [key: string]: string | number | boolean | Props;
}

export function useWidgetStore() {
  const store = useStore();

  const getStoredData = (module: StoreLiteModule, field?: string) => {
    const data = store.getters[module + '/data'];
    if (!data) return null;
    if (!field) return data;
    return data[field];
  };

  const getPropsFromStore = (props?: Props) => {
    if (!props) return {};
    return mapValues(props, (value) => {
      if (typeof value === 'string' && value.startsWith('$')) {
        const [module, field] = value.slice(1).split('.');
        return getStoredData(module as StoreLiteModule, field);
      }
      if (typeof value === 'object' && !isArray(value) && value !== null) {
        return getPropsFromStore(value as Props);
      }
      return value;
    });
  };

  return {
    getPropsFromStore,
  };
}
