<template>
<div>
  <modal :state="showModal">
    <error-modal :error="error" @close="showModal = false"></error-modal>
  </modal>
  <table-view :columns="columns" :data-source="fetchData" :page="pagination.page" :page-size="pageSize" :page-count="pagination.pageCount" :total-count="pagination.totalCount" @row-click="showDetails" :mouse-over="true"></table-view>

</div>

</template>

<script>

import TableView from "@/components/UI/TableView.vue";
import {useErrorLogStore} from "@/store/errorLog.js";
import {mapStores} from "pinia";
import Modal from "@/components/UI/Modal.vue";
import TraceView from "@/components/layout/TraceView.vue";
import {buildDate} from "@/common.js";
import ErrorModal from "@/components/layout/error/ErrorModal.vue";

export default {
  name: "ErrorLog",
  components: {ErrorModal, TraceView, Modal, TableView},
  data() {
    return {
      showModal: false,
      error: null,
      pageSize: 20,
      pagination: { page: 1, pageCount: 1, totalCount: 1 },
      columns: [
          {key: 'type', label: 'Type', align: "center", iconResolver: (rawValue, item) => {

              if (rawValue === "FRONTEND") {
                return "PhDesktop";
              } else if (rawValue === "BACKEND") {
                return "PhHardDrives"
              } else if (rawValue === "BULK") {
                return "PhStack"
              } else if(rawValue === "CALCULATION") {
                return "PhCalculator"
              }
            }},
          {key: 'timestamp', label: 'Timestamp', formatter: (value) => this.buildDate(value) },
          {key: 'user_id', label: 'User'},
          {key: 'title', label: 'Title'},
          {key: 'message', label: 'Message', formatter: (value) => (value?.length > 100 ? `${value?.substring(0,100)} ...`  : value)},
          {key: 'code', label: 'Exception'},

      ],
    }
  },
  computed: {
    ...mapStores(useErrorLogStore)
  },
  props: {
    isSelected: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    async isSelected(newVal) {
      if(newVal === true) {
        const query = {
          searchTerm: '',
          page: 1,
          pageSize: 20,
        }
        await this.fetchData(query);
      }
    }
  },
  methods: {

    async fetchData(query) {
      await this.errorLogStore.setQuery(query);
      this.pagination = this.errorLogStore.getPagination;
      return this.errorLogStore.getErrors;
    },
    buildDate(date) {
      return buildDate(date, true);
    },
    showDetails(error) {
      this.error = error;
      this.showModal = true;
    }
  }
}
</script>


<style scoped>

</style>