<template>
  <div style="height: 100%; width: 100%">
  <ag-grid-vue
      style="width: 100%; height: 100%;"
      class="ag-theme-material"
      @grid-ready="onGridReady"
      :defaultColDef="defaultColDef"
      :columnDefs="columnDefs"
      :pagination="true"
      :paginationAutoPageSize=true
      :row-data="null"
      row-selection="single"
      :onRowSelected="openExamineLog"
      :supress-horisontal-scroll="true"
      :enable-scrolling="true"
    ></ag-grid-vue>
    <v-dialog
        v-model="examineLog"
    >
      <v-card>
        <v-card-text>
          <v-table>
            <thead>
            <tr>
              <th class="text-left">
                Key
              </th>
              <th class="text-left">
                Value
              </th>
            </tr>
            </thead>
            <tbody>
            <tr
                v-for="item in examineLogContent"
                :key="item.name"
            >
              <td>{{ item.key }}</td>
              <td>
                <span> {{ item.value }} </span>
              </td>
            </tr>
            </tbody>
          </v-table>
        </v-card-text>
        <v-card-actions>
          <v-btn color="primary" block @click="examineLog = null">Close Dialog</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue3";
import "ag-grid-community/styles//ag-grid.css";
import "ag-grid-community/styles//ag-theme-material.css";
import ScreenshotCell from "./ScreenshotCell.js";
import { VCard, VCardText, VCardActions } from 'vuetify/components/VCard'
import { VDialog } from 'vuetify/components/VDialog'
import { VBtn } from 'vuetify/components/VBtn'
import { VTable } from 'vuetify/components/VTable'

export default {
  components: {
    AgGridVue,
    VCard,
    VCardText,
    VCardActions,
    VBtn,
    VDialog,
    VTable,
    ScreenshotCell: ScreenshotCell
  },
  data() {
    return {
      examineLog: null,
      examineLogContent: null,
      copied: false,
      gridApi: null,
      gridColumnApi: null,
      rowData: [],
      defaultColDef: {
        width: 50,
        initialPinned: true,
        resizable: true
      },
      currentRowCount: 0,
      viewRowCount: 20,
      comboBoxOptions: [],
      columnDefs:  [
        {
          field: '_id',
        },
        {
          field: 'kubernetes.namespace',
          headerName: 'namespace',
          tooltipValueGetter: (params) => params.value,
          filter: true,
        },
        {
          field: 'kubernetes.pod.name',
          headerName: 'pod',
          tooltipValueGetter: (params) => params.value,
          filter: true,
        },
        {
          field: 'kubernetes.container.name',
          headerName: 'container',
          tooltipValueGetter: (params) => params.value,
          filter: true,
        },
        {
          field: 'message',
          tooltipValueGetter: (params) => params.value,
          width: 500,
        },
        {
          field: 'stream',
        },
        {
          field: '@timestamp',
          width: 70,
          sortable: true
        }
      ],
    }
  },
  created() {
    this.setupStream()
  },
  methods: {
    setupStream() {
      let es = new EventSource('/events');
      es.onmessage = (e) => this.handleReceiveMessage(e)
    },
    onGridReady(params) {
      this.gridApi = params.api;
      this.gridColumnApi = params.columnApi;
    },
    handleReceiveMessage (event) {
      const eventData = this.parseEventData(event.data);
      this.gridApi.updateRowData({add: [eventData]});
      this.gridApi.sizeColumnsToFit()
    },
    refreshRowData () {
      const itemsToUpdate = [];
      this.rowData.slice(0 - this.viewRowCount).forEach((row, index) => {
        row.index = index
        itemsToUpdate.push(row)
      });
      this.gridApi.applyTransactionAsync({ update: itemsToUpdate });
      this.gridApi.sizeColumnsToFit()
      this.getComboBoxOptions()
    },
    parseEventData (eventData) {
      try {
        let json = JSON.parse(eventData)
        if (!json.message) {
          json.message = JSON.stringify(json.json)
        }
        return json
      } catch (e) {
        console.error(e, eventData)
      }
    },
    openExamineLog (row) {
      const selectedRow = row.data
      row.node.setSelected(false)
      this.examineLog = true
      const flattened = flattenObj(selectedRow)
      const pairs = [];
      Object.keys(flattened).map((key) => {
        pairs.push({
          key: key,
          value: flattened[key]
        })
      })
      this.examineLogContent = pairs
    }
  },
}

const flattenObj = (ob) => {
  let result = {};
  for (const i in ob) {
    if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
      const temp = flattenObj(ob[i]);
      for (const j in temp) {
        result[i + '.' + j] = temp[j];
      }
    }
    else {
      result[i] = ob[i];
    }
  }
  return result;
};
</script>
