<template>
  <q-menu ref="refMenu" context-menu>
    <q-list>
      <q-item :disable="!startEnabled" clickable @click="start">
        <q-item-section>
          <q-icon :color="startEnabled ? 'green' : 'green-2'" name="play_arrow" size="sm" />
        </q-item-section>
      </q-item>
      <q-item :disable="!stopEnabled" clickable @click="stop">
        <q-item-section>
          <q-icon :color="stopEnabled ? 'red' : 'red-2'" name="stop" size="sm" />
        </q-item-section>
      </q-item>
      <q-item :disable="!restartEnabled" clickable>
        <q-item-section>
          <q-icon
            :color="restartEnabled ? 'orange' : 'orange-3'"
            name="restart_alt"
            size="sm"
            @click="console.log('restart')"
          />
        </q-item-section>
      </q-item>
    </q-list>
  </q-menu>
</template>

<script lang="ts" setup>
import { appApi } from 'src/boot/axios';
import type { Service } from 'src/vueLib/models/Services';
import { computed, ref } from 'vue';
import { useNotify } from 'src/vueLib/general/useNotify';

const { NotifyResponse } = useNotify();

const refMenu = ref();
const startEnabled = computed(() => localService.value?.state === 'Stopped' || 'Error');
const stopEnabled = computed(() => localService.value?.state === 'Running');
const restartEnabled = computed(() => localService.value?.state === 'Running');
const localService = ref<Service>();

const open = (event: MouseEvent, service: Service) => {
  localService.value = service;
  refMenu.value?.show(event);
};

function start() {
  if (!localService.value) {
    return;
  }
  localService.value.state = 'Starting';
  localService.value.stateColor = 'yellow';
  localService.value.stateTextColor = 'black';
  appApi
    .get(`/services/${localService.value.name}/start`)
    .then(() => {
      if (!localService.value) {
        return;
      }
      localService.value.state = 'Running';
      localService.value.stateColor = 'green';
      localService.value.stateTextColor = 'white';
    })
    .catch((err) => {
      console.error(err);
      NotifyResponse(err, 'error');
    });
}

function stop() {
  if (!localService.value) {
    return;
  }
  localService.value.state = 'Stopping';
  localService.value.stateColor = 'yellow';
  localService.value.stateTextColor = 'black';

  appApi
    .get(`/services/${localService.value.name}/stop`)
    .then(() => {
      if (!localService.value) {
        return;
      }
      localService.value.state = 'Stopped';
      localService.value.stateColor = 'grey-4';
      localService.value.stateTextColor = 'black';
    })
    .catch((err) => NotifyResponse(err, 'error'));
}

defineExpose({ open });
</script>
