import {
  ActionTree,
  GetterTree,
  mapActions,
  mapGetters,
  Mapper,
  mapState,
  MutationTree,
} from 'vuex';
import axios from 'axios';
import get from 'lodash/get';
import { Dark } from 'quasar';
import { timezones } from '@utils/constants/timezones';

interface State {
  theme: string;
  themes: {
    dark: string;
    light: string;
  };
  timezone: string;
  timezones: typeof timezones;
}

export const state: State = {
  theme: 'light',
  themes: {
    dark: 'app.themes.dark',
    light: 'app.themes.light',
  },
  timezone: 'Europe/Moscow',
  timezones: timezones,
};

export const getters: GetterTree<State, State> = {
  theme(state) {
    return state.theme;
  },
  themes(state) {
    return state.themes;
  },
  timezone(state) {
    return state.timezone;
  },
  timezones(state) {
    return state.timezones;
  },
};

export const mutations: MutationTree<State> = {
  theme(state, theme) {
    state.theme = theme;
  },
  themes(state, themes) {
    state.themes = themes;
  },
  timezone(state, timezone) {
    state.timezone = timezone;
  },
  timezones(state, timezones) {
    state.timezones = timezones;
  },
};

export const actions: ActionTree<State, State> = {
  dispatchTheme({ commit }: any = {}, { theme }) {
    commit('theme', theme);

    switch (theme) {
      case 'dark':
        Dark.set(true);

        break;
      case 'light':
        Dark.set(false);

        break;
    }
  },
  dispatchThemes({ commit }: any = {}, { themes }) {
    commit('themes', themes);
  },
  dispatchTimezone({ commit }: any = {}, { timezone }) {
    commit('timezone', timezone);
  },
  dispatchTimezones({ commit }: any = {}, { timezones }) {
    commit('timezones', timezones);
  },
  fetchResource(store, { name }) {
    return new Promise((resolve, reject) => {
      axios
        .get(
          `${
            process.env.VUE_APP_PROJECT_PATH || ''
          }/service/app-resources/${name}`
        )
        .then((response) => {
          const data =
            get(
              {
                response,
              },
              'response.data'
            ) || '';

          return resolve(data.toString());
        })
        .catch((e) => {
          return reject(e);
        });
    });
  },
};

export const utilsAppComputed = {
  ...mapState<Mapper<State>>('utils/app', {
    theme: (state: State) => state.theme,
    themes: (state: State) => state.themes,
    timezone: (state: State) => state.timezone,
    timezones: (state: State) => state.timezones,
  }),
  ...mapGetters('utils/app', ['theme', 'themes', 'timezone', 'timezones']),
};

export const utilsAppMethods = mapActions('utils/app', [
  'dispatchTheme',
  'dispatchTimezone',
  'dispatchTimezones',
  'dispatchThemes',
  'fetchResource',
]);
