<script setup>

import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;

import { computed, reactive, onMounted, ref, useTemplateRef } from 'vue';
import { Button, Menu, TableView, ProgressBar, FormGroup, Checkbox, Dialog } from '@cloudron/pankow';
import { prettyBinarySize } from '@cloudron/pankow/utils';
import { each } from 'async';
import Section from '../components/Section.vue';
import StateLED from '../components/StateLED.vue';
import ServicesModel from '../models/ServicesModel.js';
import SystemModel from '../models/SystemModel.js';
import AppsModel from '../models/AppsModel.js';

const appsModel = AppsModel.create();
const servicesModel = ServicesModel.create();
const systemModel = SystemModel.create();

const columns = {
  status: {},
  name: {
    label: t('services.service'),
    sort: true
  },
  memoryPercent: {
    label: t('services.memoryUsage'),
    sort: true,
    hideMobile: true,
  },
  memoryLimit: {
    label: t('services.memoryLimit'),
    sort: true,
    hideMobile: true,
  },
  actions: {}
};

const actionMenuModel = ref([]);
const actionMenuElement = useTemplateRef('actionMenuElement');
function onActionMenu(service, event) {
  actionMenuModel.value = [{
    icon: 'fa-solid fa-pencil-alt',
    label: t('main.action.edit'),
    visible: service.status !== 'disabled' && service.memoryLimit,
    action: onEdit.bind(null, service),
  }, {
    separator: true,
    visible: service.status !== 'disabled' && service.memoryLimit,
  }, {
    icon: 'fa-solid fa-sync-alt',
    label: t('services.restartActionTooltip'),
    visible: service.id !== 'box',
    disabled: (service.status === 'starting' && !service.config.recoveryMode),
    action: onRestart.bind(null, service.id),
  }, {
    icon: 'fa-solid fa-fw fa-file-alt',
    label: t('logs.title'),
    target: '_blank',
    href: `/logs.html?id=${service.id}`,
  }];

  actionMenuElement.value.open(event, event.currentTarget);
}

const services = reactive({
  box: {
    name: 'cloudron',
    status: 'active',
    memoryUsage: 0,
    memoryLimit: 0,
    config: {}
  }
});

const servicesArray = computed(() => {
  return Object.keys(services).map(s => {
    services[s].id = s;
    return services[s];
  });
});

async function refresh(id) {
  const [error, result] = await servicesModel.get(id);
  if (error) return console.error(error);

  services[id] = result;
  services[id].id = id;
  services[id].name = id.indexOf('redis') === 0 ? services[id].name : result.name;
  services[id].config = result.config || {};
  services[id].memoryLimit = result.config.memoryLimit || 0;
  services[id].memoryUsed = result.memoryUsed || 0;
  services[id].memoryPercent = result.memoryPercent || 0;

  if (id.indexOf('redis') === 0) {
    // eslint-disable-next-line no-unused-vars
    const [error, result] = await appsModel.get(id.slice('redis:'.length));
    if (result) services[id].name = 'Redis (' + (result.label || result.fqdn) + ')';
    else services[id].name = 'Redis (unknown app)';
  }

  // we will poll until active
  if (result.status !== 'active') setTimeout(refresh.bind(null, id), 3000);
}

const refreshBusy = ref(false);
async function refreshAll() {
  refreshBusy.value = true;
  const [error, serviceList] = await servicesModel.list();
  if (error) return console.error(error);

  // init with all services
  for (const s of serviceList.sort()) {
    if (!services[s]) services[s] = { id: s, name: s, config: {} };
  }

  await each(serviceList, refresh);
  refreshBusy.value = false;
}

async function onRestart(id) {
  services[id].status = 'starting';

  const [error] = await servicesModel.restart(id);
  if (error) return console.error(error);

  // this will poll till active
  await refresh(id);
}

const dialog = useTemplateRef('dialog');
const editService = ref({});
const editError = ref('');
const editBusy = ref(false);
const editMemoryLimit = ref(0);
const editMemoryTicks = ref([]);
const editRecoveryMode = ref(false);

let availableSystemMemory = 4 * 1024 * 1024 * 1024;

async function onEdit(service) {
  editService.value = service;
  editMemoryLimit.value = service.config.memoryLimit;
  editRecoveryMode.value = service.config.recoveryMode;

  editMemoryTicks.value = [];
  // we max system memory and current service memory for the case where the user configured the service on another server with more resources
  const nearest256m = Math.ceil(Math.max(availableSystemMemory, editService.value.config.memoryLimit) / (256*1024*1024)) * 256 * 1024 * 1024;
  const startTick = editService.value.defaultMemoryLimit;

  // code below ensure we atleast have 2 ticks to keep the slider usable
  editMemoryTicks.value.push(startTick); // start tick
  for (let i = startTick * 2; i < nearest256m; i *= 2) editMemoryTicks.value.push(i);
  editMemoryTicks.value.push(nearest256m); // end tick

  dialog.value.open();
}

function onResetToDefaults() {
  editMemoryLimit.value = editService.value.defaultMemoryLimit;
}

async function onEditSubmit() {
  editBusy.value = true;

  const [error] = await servicesModel.update(editService.value.id, parseInt(editMemoryLimit.value), editRecoveryMode.value);
  if (error) {
    console.error(error);
    editError.value = error.body ? error.body.message : 'Internal Error';
    editBusy.value = false;
    return;
  }

  await refresh(editService.value.id);
  editBusy.value = false;
  dialog.value.close();
}

function state(service) {
  if (service.status === 'active') return 'success';
  else if (service.status === 'starting' && service.config.recoveryMode) return '';
  else if (service.status === 'starting') return 'warning';
  else return 'danger';
}

function stateTooltip(service) {
  if (!service.status) return '';

  if (service.status === 'active') return 'Active';
  else if (service.status === 'starting' && service.config.recoveryMode) return 'Recovery mode';
  else if (service.status === 'starting') return 'Starting';
  else return service.status;
}

onMounted(async () => {
  await refreshAll();

  const [error, result] = await systemModel.memory();
  if (error) return console.error(error);
  availableSystemMemory = result.memory;
});

</script>

<template>
  <div class="content">
    <Menu ref="actionMenuElement" :model="actionMenuModel" />
    <Dialog ref="dialog"
      :title="$t('services.configure.title', { name: editService.name })"
      :confirm-busy="editBusy"
      :confirm-label="$t('main.dialog.save')"
      :reject-label="$t('main.dialog.cancel')"
      reject-style="secondary"
      @confirm="onEditSubmit()"
    >
      <p class="has-error text-center" v-show="editError">{{ editError }}</p>

      <FormGroup>
        <label for="memoryLimitInput">{{ $t('services.memoryLimit') }}: {{ prettyBinarySize(editMemoryLimit) }}</label>
        <input type="range" style="margin: 4px" id="memoryLimitInput" v-model="editMemoryLimit" step="134217728" :min="editMemoryTicks[0]" :max="editMemoryTicks[editMemoryTicks.length-1]" list="memoryLimitTicks" />
        <datalist id="memoryLimitTicks">
          <option v-for="limit in editMemoryTicks" :value="limit" :key="limit"></option>
        </datalist>
      </FormGroup>
      <Button style="float: right;" small @click="onResetToDefaults()">{{ $t('services.configure.resetToDefaults') }}</Button>
      <br/>
      <br/>
      <Checkbox v-model="editRecoveryMode" :label="$t('services.configure.enableRecoveryMode')" />
      <p v-html="$t('services.configure.recoveryModeDescription', { docsLink: 'https://docs.cloudron.io/troubleshooting/#unresponsive-service' })"></p>
    </Dialog>

    <Section :title="$t('services.title')">
      <template #header-buttons>
        <Button tool secondary @click="refreshAll()" :loading="refreshBusy" :disabled="refreshBusy" icon="fa-solid fa-sync-alt"/>
      </template>

      <div>{{ $t('services.description') }}</div>
      <br/>

      <TableView :columns="columns" :model="servicesArray">
        <template #status="service">
          <StateLED :busy="!service.status" :state="state(service)" :title="stateTooltip(service)"/>
        </template>
        <template #memoryPercent="service">
          <ProgressBar :value="service.memoryPercent" v-show="service.memoryPercent" />
        </template>
        <template #memoryLimit="service">
          <span v-show="service.memoryLimit">{{ prettyBinarySize(service.memoryLimit) }}</span>
        </template>
        <template #actions="service">
          <div style="text-align: right;">
            <Button tool plain secondary @click.capture="onActionMenu(service, $event)" icon="fa-solid fa-ellipsis" />
          </div>
        </template>
      </TableView>
    </Section>
  </div>
</template>
