<template>
  <div>
    <q-card>
      <q-card-section>
        <div class="text-bold text-primary">Services</div>
      </q-card-section>
      <div class="row justify-center">
        <q-card-section class="col-8">
          <div class="q-py-md text-grey text-left">
            <div v-if="driverRows?.length == 0">No services available</div>
            <q-btn
              no-caps
              rounded
              color="primary"
              :style="'font-size: 12px;'"
              :class="[, 'text-bold', 'text-white']"
              :disable="userStore.user?.role !== 'admin'"
              @click="addNewDriver"
            >
              Add {{ driverRows?.length == 0 ? 'First' : '' }} Service
            </q-btn>
          </div>
          <q-table v-if="driverRows?.length > 0" :rows="driverRows" :columns="columns">
            <template v-slot:body-cell-settings="props">
              <q-td :props="props">
                <q-btn
                  dense
                  flat
                  size="md"
                  icon="more_vert"
                  @click="openSubMenu($event, props.row)"
                ></q-btn>
              </q-td>
            </template>
            <template v-slot:body-cell-state="props">
              <q-td :props="props">
                <q-badge
                  :color="props.row.stateColor"
                  :text-color="props.row.stateTextColor"
                  :label="props.row.state"
                />
              </q-td>
            </template>
          </q-table>
        </q-card-section>
      </div>
      <sub-menu ref="subMenuRef" />
    </q-card>

    <service-dialog ref="refServiceDialog"></service-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRef } from 'vue';
import { useQuasar, type QTableProps } from 'quasar';
import { useUserStore } from 'src/vueLib/login/userStore';
import ServiceDialog from 'src/vueLib/services/dialog/ServiceDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import type { Service, Services, State } from 'src/vueLib/models/Services';
import { useServices } from 'src/vueLib/models/Services';
import SubMenu from 'src/vueLib/services/dialog/SubMenu.vue';
import { useStatusServer } from 'src/vueLib/services/statusServer/useStatusServer';

const { NotifyResponse } = useNotify();

const userStore = useUserStore();
const refServiceDialog = ref();
const { initServices } = useServices();
const driverRows = reactive<Services>([]);
const { connect, subscribe } = useStatusServer(
  '127.0.0.1',
  9500,
  'api/status',
  'quasar',
  (response) => {
    // normalize topic to service name
    const serviceName = response.topic.replace('status/', '').replace(' ', '');
    const driver = driverRows.find((d) => d.name.replace(' ', '') === serviceName);

    if (driver && response.data?.state !== undefined) {
      // update state reactively
      driver.state = response.data?.state as State;

      // update colors depending on state
      switch (driver.state) {
        case 'Running':
          driver.stateColor = 'green';
          driver.stateTextColor = 'white';
          break;
        case 'Starting':
          driver.stateColor = 'orange';
          driver.stateTextColor = 'black';
          break;
        case 'Stopping':
          driver.stateColor = 'orange';
          driver.stateTextColor = 'black';
          break;
        case 'Error':
          driver.stateColor = 'red';
          driver.stateTextColor = 'white';
          NotifyResponse(response.data?.message, 'error');
          break;
        case 'Stopped':
        default:
          driver.stateColor = 'grey-4';
          driver.stateTextColor = 'black';
          break;
      }
    }
  },
  useQuasar(),
);

const subMenuRef = ref();

const columns = [
  { name: 'name', label: 'Name', field: 'name', align: 'left', style: 'font-size:12px;' },
  {
    name: 'description',
    label: 'Description',
    field: 'description',
    align: 'center',
    style: 'font-size:12px;',
  },
  {
    name: 'settings',
    label: '',
    field: 'settings',
    align: 'center',
  },
  {
    name: 'state',
    label: 'State',
    field: 'state',
    align: 'left',
  },
] as QTableProps['columns'];

onMounted(() => {
  initServices()
    .then((resp) => {
      driverRows.push(...resp);
    })
    .catch((err) => NotifyResponse(err, 'error'));
  connect();
  subscribe('*').catch((err) => NotifyResponse(err, 'error'));
});

function addNewDriver() {
  refServiceDialog.value.open();
}

function openSubMenu(event: Event, service: Service) {
  subMenuRef.value?.open(event, toRef(driverRows.find((d) => d.name === service.name)!));
}
</script>
