import { defineStore } from "pinia";
import loadingStore from './loading.js';
import pinia from '@/stores/main.js'
import axios from "axios";
import moment from 'moment';
import apiError from '@/module/apiError.js';

const loading = loadingStore(pinia);

export default defineStore('filesStore', {
  state: () => ({
    allFilter: [
      {
        log: {},
        fileType: '',
        ownerName: '',
      }
    ],
    allEventLog: [
      {
        parentLog: '',
        fileType: '',
        ownerName: '',
      }
    ],
    switchFilesTagData: {
      ALL: ['Log', 'Filter', 'Rule', 'Design'],
      DISCOVER: ['Log', 'Filter', 'Rule'],
      COMPARE: ['Log','Filter'],
      DESIGN: ['Log', 'Design'],
    },
    filesTag: 'ALL',
    httpStatus: 200,
  }),
  getters: {
  /**
   * Get allFiles and switch files tag
   */
  allFiles: state => {
    let result = [
      ...state.allEventLog,
      ...state.allFilter
    ];
    let data = state.switchFilesTagData;
    let filesTag = state.filesTag;

    result = result.filter(file => data[filesTag].includes(file.fileType));

    return result;
    },
  },
  actions: {
    /**
     * Fetch event logs api
     */
    async fetchEventLog() {
      const api = '/api/logs';

      try {
        const response = await axios.get(api);

        this.allEventLog = response.data;
        this.allEventLog.map(o => {
          o.icon = 'work_history';
          o.parentLog = o.name;
          o.fileType = "Log";
          o.ownerName = o.owner.name;
          o.updated_base = o.updated_at;
          o.accessed_base = o.accessed_at;
          o.updated_at = moment(o.updated_at).utcOffset('+08:00').format('YYYY-MM-DD HH:mm');
          o.accessed_at = o.accessed_at ? moment(o.accessed_at).utcOffset('+08:00').format('YYYY-MM-DD HH:mm') : null;
          return this.allEventLog
        })
        if(this.httpStatus < 300) loading.isLoading = false;
      } catch(error) {
        apiError(error, 'Failed to load the logs.');
      };
    },
    /**
     * Fetch filters api
     */
    async fetchFilter() {
      const api = '/api/filters';

      try {
        const response = await axios.get(api);

        this.allFilter = response.data;
        this.allFilter.map(o => {
          o.icon = 'tornado';
          o.parentLog = o.log.name;
          o.fileType = "Filter";
          o.ownerName = o.owner.name;
          o.updated_base = o.updated_at;
          o.accessed_base = o.accessed_at;
          o.updated_at = moment(o.updated_at).utcOffset('+08:00').format('YYYY-MM-DD HH:mm');
          o.accessed_at = o.accessed_at ? moment(o.accessed_at).utcOffset('+08:00').format('YYYY-MM-DD HH:mm') : null;
        });
        if(this.httpStatus < 300) loading.isLoading = false;
      } catch(error) {
        apiError(error, 'Failed to load the filters.');
      };
    },
    // fetchRule(){o.icon = local_police}
    // fetchDesign(){o.icon = shape_line}
  },
})
