import { defineStore } from "pinia";
import apiError from '@/module/apiError.js';

export default defineStore('compareStore', {
  state: () => ({
    allCompareDashboardData: null,
  }),
  getters: {
    compareDashboardData: state => {
      return state.allCompareDashboardData;
    },
  },
  actions: {
    /**
     * Get Performance
     * @param { array } queryParams
     */
    async getCompare(queryParams) {
      // encodeURIComponent 函數用於將字串中的特殊字符進行編碼，以確保 URL 的正確性。
      const queryString = JSON.stringify(queryParams);
      const api = `/api/compare?datasets=${encodeURIComponent(queryString)}`;

      try {
        const response = await this.$axios.get(api);
        this.allCompareDashboardData = response.data;
      } catch(error) {
        apiError(error, 'Failed to load the Compare.');
      }
    },
    /**
     * fetch discover api, get stats.
     */
    async getStateData(type, id) {
      let api = '';

      switch (type) {
        case 'log':
          api = `/api/logs/${id}/discover`;
          break;
        case 'filter':
          api = `/api/filters/${id}/discover`
          break;
      }
      try {
        const response = await this.$axios.get(api);

        return response.data.stats;
      } catch(error) {
        apiError(error, "Failed to load the Compare's States.");
      };
    },
    /**
     * Get file's name
     */
    async getFileName(id) {
      id = Number(id)
      try {
        const response = await this.$axios.get('/api/files');
        const file = response.data.find(i => i.id === id);

        if(file) return file.name;
      } catch(error) {
        apiError(error, "Failed to load the Compare's file name.");
      }
    }
  },
})
