<script setup>

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;

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

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

const appsModel = AppsModel.create(API_ORIGIN, localStorage.token);
const servicesModel = ServicesModel.create(API_ORIGIN, localStorage.token);
const systemModel = SystemModel.create(API_ORIGIN, localStorage.token);

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

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 ? id : 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) {
    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 onEditConfirm() {
  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;
  }

  setTimeout(() => refresh(editService.value.id), 2000);
  editBusy.value = false;
  dialog.value.close();
}

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

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

</script>

<template>
  <div class="content">
    <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="onEditConfirm()"
    >
      <p class="has-error text-center" v-show="editError">{{ editError }}</p>

      <FormGroup>
        <label for="memoryLimitInput">{{ $t('services.memoryLimit') }}: {{ prettyBinarySize(editService.memoryLimit) }}</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 @click="refreshAll()" :loading="refreshBusy">{{ $t('services.refresh') }}</Button>
      </template>

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

      <TableView :columns="columns" :model="servicesArray" :hover="false">
        <template #status="slotProps">
          <span v-show="slotProps.status">
            <span v-if="slotProps.status === 'active'">
              <i class="fa fa-circle status-active" v-tooltip="'active'"></i>
            </span>
            <span v-else-if="slotProps.status === 'starting'">
              <i class="fa fa-circle status-starting" v-tooltip="'starting'" v-show="!slotProps.config.recoveryMode"></i>
              <i class="fa fa-circle status-inactive" v-tooltip="'recovery mode'" v-show="slotProps.config.recoveryMode"></i>
            </span>
            <span v-else>
              <i class="fa fa-circle status-error" uib-tooltip="{{ slotProps.status }}"></i>
            </span>
          </span>
          <i class="fa fa-circle-notch fa-spin" v-show="!slotProps.status"></i>
        </template>
        <template #memoryPercent="slotProps">
          <ProgressBar :value="slotProps.memoryPercent" v-show="slotProps.memoryPercent" />
        </template>
        <template #memoryLimit="slotProps">
          <span v-show="slotProps.memoryLimit">{{ prettyBinarySize(slotProps.memoryLimit) }}</span>
        </template>
        <template #actions="slotProps">
          <div class="table-actions">
            <ButtonGroup>
              <Button small tool secondary outline v-if="slotProps.status !== 'disabled' && slotProps.config.memoryLimit" @click="onEdit(slotProps)" v-tooltip="$t('services.configureActionTooltip')" icon="fa-solid fa fa-pencil-alt"/>
              <Button small tool secondary outline v-if="slotProps.id !== 'box'" @click="onRestart(slotProps.id)" :loading="slotProps.status === 'starting' && !slotProps.config.recoveryMode" v-tooltip="$t('services.restartActionTooltip')" icon="fa-solid fa-sync-alt"/>
              <Button tool small secondary outline :href="`/logs.html?id=${slotProps.id}`" target="_blank" v-tooltip="$t('logs.title')" icon="fa-solid fa-file-alt" />
            </ButtonGroup>
          </div>
        </template>
      </TableView>
    </Section>
  </div>
</template>
