
import { defineStore } from 'pinia';
import { UiFlavorProvider, UiIconSet, UiSection, UiSettingsGroup, UiStoreState } from 'zero/ui';
import api from './api';

const THEME_KEY = 'zero.theme';

export let sectionMods = [];
export let settingsMods = [];

export const useUiStore = defineStore('zero.ui', {
  state: () => ({
    preferences: {
      theme: 'dark'
    },

    sections: [],
    settingGroups: [],
    iconSets: [],
    flavors: [],
    blueprints: []
  } as UiStoreState),

  actions: {
    async setup(anonymous)
    {
      this.setTheme(localStorage.getItem(THEME_KEY) || 'default');

      if (anonymous)
      {
        return;
      }

      const values = await Promise.all([
        api.getSections(),
        api.getSettingGroups(),
        api.getIconSets(),
        api.getFlavors(),
        api.getBlueprints()
      ]);

      this.sections = values[0].data as UiSection[];
      this.settingGroups = values[1].data as UiSettingsGroup[];
      this.iconSets = values[2].data as UiIconSet[];
      this.flavors = values[3].data as Record<string, UiFlavorProvider>;
      this.blueprints = values[4].data as string[];

      sectionMods.forEach(mod =>
      {
        mod(this.sections);
      });

      settingsMods.forEach(mod =>
      {
        mod(this.settingGroups);
      });
    },

    getFlavors(alias: string)
    {
      let flavorConfig = this.flavors[alias] || {
        canUseWithoutFlavors: true,
        flavors: []
      } as UiFlavorProvider;

      let flavors = JSON.parse(JSON.stringify(flavorConfig.flavors));

      if (flavorConfig.canUseWithoutFlavors && flavors.length > 0)
      {
        flavors.splice(0, 0, {
          name: '@flavors.default.name',
          description: '@flavors.default.text',
          alias: null,
          icon: 'fth-box'
        });
      }

      return flavors;
    },

    setTheme(theme: 'default' | 'light' | 'dark')
    {
      const dark = theme === 'dark';
      this.preferences.theme = theme;
      localStorage.setItem(THEME_KEY, theme);

      document.body.classList.toggle('theme-light', !dark);
      document.body.classList.toggle('theme-dark', dark);
    }
  }
});