import { defineStore } from 'pinia';
import { api } from 'boot/axios';
import { IAppDisplay, IAppVersion, IAppVersionDisplay, IManagedApp, IVersionSubmit } from 'src/types/AppTypes';
import { date, Notify } from 'quasar'
import { userToUserDisplay } from './useUserStore';


export const useAppStore = defineStore('app', {
  state: () => ({
    apps: [] as IAppDisplay[],
    rowIds: new Set<string>(),
  }),
  actions: {
    async loadApps() {
      this.reset();
      try {
        const { data } = await api.get('api/apps');
        this.apps = data.data.map((item: IManagedApp) => {
          this.rowIds.add(item.appid);
          return appToAppDisplay(item)
        }).sort((a: IAppDisplay, b: IAppDisplay) => a.sortId - b.sortId); // set default order
      } catch (error) {
        Notify.create({
          icon: 'error',
          color: 'negative',
          message: 'アプリ一覧の読み込みに失敗しました'
        })
      }
    },

    getAppById(id: string) {
      if (!this.rowIds.has(id)) {
        return null;
      }
      return this.apps.find((item: IAppDisplay) => item.id === id);
    },

    async deleteApp(app: IAppDisplay) {
      try {
        await api.delete(`api/apps/${app.id}`);
      } catch (error) {
        console.error(error);
        Notify.create({
          icon: 'error',
          color: 'negative',
          message: 'アプリの削除に失敗しました'
        });
        return false;
      }
      return true;
    },

    async getVersionsByAppId(app: IAppDisplay) {
      const { data } = await api.get(`api/appversions/${app.id}`);
      return data.data.map((item: IAppVersion) => versionToVersionDisplay(item));
    },

    async changeVersion(app: IAppDisplay, version: IAppVersionDisplay) {
      await api.put(`api/appversions/${app.id}/${version.id}`);
    },

    async createVersion(versionSubmit: IVersionSubmit) {
      await api.post('api/apps', {
        'appid': versionSubmit.appId,
        'versionname': versionSubmit.name,
        'comment': versionSubmit.comment
      })
    },

    reset() {
      this.apps = [];
      this.rowIds.clear();
    },
  },
});

function versionToVersionDisplay(item: IAppVersion) {
  return {
    id: item.version,
    version: item.version,
    appid: item.appid,
    name: item.versionname,
    comment: item.comment,
    updater: userToUserDisplay(item.updateuser),
    updateTime: formatDate(item.update_time),
    creator: userToUserDisplay(item.createuser),
    createTime: formatDate(item.create_time),
  } as IAppVersionDisplay;
}

function appToAppDisplay(app: IManagedApp) {
  return {
    id: app.appid,
    sortId: parseInt(app.appid, 10),
    name: app.appname,
    url: `${app.domainurl}/k/${app.appid}`,
    version: app.version,
    versionName: app.versionname,
    updateTime: formatDate(app.update_time),
    updateUser: userToUserDisplay(app.updateuser),
    versionChanged: app.is_saved
  } as IAppDisplay
}

function formatDate(data: string) {
  return date.formatDate(new Date(data + 'Z'), 'YYYY/MM/DD HH:mm');
}
