<script setup>

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

import { computed, reactive, onMounted, ref, useTemplateRef, nextTick, onUnmounted } from 'vue';
import { Button, 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 ActionBar from '../components/ActionBar.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 BOX_SERVICE = Object.freeze({
  id: 'box',
  name: 'cloudron',
  status: 'active',
  memoryUsed: 0,
  memoryPercent: 0,
  memoryLimit: 0,
  config: {}
});

const columns = {
  status: {},
  name: {
    label: t('services.service'),
    sort: true,
    width: '30%'
  },
  memoryPercent: {
    label: t('services.memoryUsage'),
    sort: false,
    hideMobile: true,
  },
  actions: {
    width: '150px'
  }
};

function createActionMenu(id) {
  return [{
    icon: 'fa-solid fa-pencil-alt',
    label: t('main.action.configure'),
    disabled: refreshBusy.value,
    visible: services[id].status !== 'disabled' && services[id].memoryLimit,
    quickAction: false,
    action: onEdit.bind(null, id),
  }, {
    separator: true,
    visible: services[id].status !== 'disabled' && services[id].memoryLimit,
  }, {
    icon: 'fa-solid fa-sync-alt',
    label: t('services.restartActionTooltip'),
    visible: id !== 'box' && services[id].status !== 'disabled',
    disabled: services[id].status === 'starting' && services[id].config.recoveryMode,
    quickAction: true,
    action: onRestart.bind(null, id),
  }, {
    icon: 'fa-solid fa-fw fa-file-alt',
    label: t('logs.title'),
    target: '_blank',
    href: `/logs.html?id=${id}`,
    quickAction: true
  }];
}

const services = reactive({});

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

let apps = [];
const servicesTimers = {};

async function refresh(id) {
  if (servicesTimers[id]) {
    clearTimeout(servicesTimers[id]);
    delete servicesTimers[id];
  }

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

  services[id].id = id;
  services[id].status = result.status;
  services[id].config = result.config || {};
  services[id].memoryLimit = result.config.memoryLimit || 0;
  services[id].memoryUsed = result.memoryUsed || 0;
  services[id].memoryPercent = result.memoryPercent || 0;
  services[id].defaultMemoryLimit = result.defaultMemoryLimit;

  // we will poll until active (idle services are intentionally stopped, no need to poll)
  if (result.status !== 'active' && result.status !== 'idle' && !result.config.recoveryMode) servicesTimers[id] = setTimeout(refresh.bind(null, id), 3000);
}

const refreshBusy = ref(false);
const initialLoadBusy = ref(true);
async function refreshAll() {
  refreshBusy.value = true;

  let [error, result] = await appsModel.list();
  if (error) {
    refreshBusy.value = false;
    return console.error(error);
  }

  apps = result;

  [error, result] = await servicesModel.list();
  if (error) {
    refreshBusy.value = false;
    return console.error(error);
  }

  const allServices = result;
  if (!services[BOX_SERVICE.id]) services[BOX_SERVICE.id] = { ...BOX_SERVICE, config: {} };

  // init with all services
  for (const s of allServices.sort((a, b) => a.name.localeCompare(b.name))) {
    if (!services[s.id]) services[s.id] = { id: s.id, name: s.name, config: {}, status: '' };

    if (s.id.indexOf('redis') === 0) {
      const app = apps.find(a => a.id === s.id.slice('redis:'.length));
      if (app) services[s.id].name = `redis (${app.label || app.fqdn})`;
      else services[s.id].name = 'redis (unknown app)';
    }
  }

  await each(allServices.map(s => s.id), refresh);
  initialLoadBusy.value = false;
  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(id) {
  editService.value = services[id];
  editMemoryLimit.value = services[id].config.memoryLimit;
  editRecoveryMode.value = services[id].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

  // unclear why this is needed for the slider value to update, but well
  await nextTick();

  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) {
   switch (service.status) {
   case 'active': return 'success';
   case 'idle': return 'idle';
   case 'disabled': return '';
   case 'stopped': return 'danger';
   case 'error': return 'danger';
   case 'starting': return service.config.recoveryMode ? '' : 'warning';
   default: return 'danger';
   }
}

function stateTooltip(service) {
   switch (service.status) {
   case 'active': return 'Active';
   case 'idle': return 'Idle (starts on demand)';
   case 'disabled': return 'Disabled';
   case 'stopped': return 'Stopped';
   case 'error': return 'Error';
   case 'starting': return service.config.recoveryMode ? 'Recovery mode' : 'Starting';
   default: return service.status;
   }
}

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

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

onUnmounted(() => {
  Object.values(servicesTimers).forEach(clearTimeout);
});

</script>

<template>
  <div class="content">
    <Dialog ref="dialog"
      :title="$t('services.configure.title')"
      :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>

      <p>{{ $t('services.configure.description', { name: editService.name }) }}</p>

      <FormGroup>
        <label for="memoryLimitInput" style="display: flex; justify-content: space-between;">
          <span>{{ $t('services.memoryLimit') }}: {{ prettyBinarySize(editMemoryLimit) }}</span>
            <Button small outline @click="onResetToDefaults()">{{ $t('services.configure.resetToDefaults') }}</Button>
        </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>
      <br/>
      <Checkbox v-model="editRecoveryMode" :label="$t('services.configure.enableRecoveryMode')" helpUrl="https://docs.cloudron.io/troubleshooting/#unresponsive-service"/>
    </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/>

      <ProgressBar v-if="initialLoadBusy" mode="indeterminate" :show-label="false" :slim="true" :show-track="false"/>

      <TableView v-if="!initialLoadBusy" :columns="columns" :model="servicesArray">
        <template #status="{ item:service }">
          <StateLED :busy="!service.status" :state="state(service)" :title="stateTooltip(service)"/>
        </template>
        <template #memoryPercent="{ item:service }">
          <ProgressBar :value="service.memoryPercent" v-show="service.memoryPercent">
            <span style="font-weight: normal">{{ prettyBinarySize(service.memoryUsed) }} / {{ prettyBinarySize(service.memoryLimit) }} ({{ service.memoryPercent }}%)</span>
          </ProgressBar>
        </template>
        <template #memoryLimit="{ item:service }">
          <span v-show="service.memoryLimit">{{ prettyBinarySize(service.memoryLimit) }}</span>
        </template>
        <template #actions="{ item:service }">
          <ActionBar :actions="createActionMenu(service.id)"/>
        </template>
      </TableView>
    </Section>
  </div>
</template>
