<script setup>

import { ref, onMounted } from 'vue';
import { Button, ProgressBar } from '@cloudron/pankow';
import { prettyLongDate } from '@cloudron/pankow/utils';
import { TASK_TYPES } from '../constants.js';
import Section from '../components/Section.vue';
import TasksModel from '../models/TasksModel.js';
import DomainsModel from '../models/DomainsModel.js';

const taskModel = TasksModel.create();
const domainsModel = DomainsModel.create();

const lastTask = ref({});
const taskLogsMenu = ref([]);

async function waitForLastTask() {
  if (!lastTask.value.id) return;

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

  lastTask.value = result;

  // task done, refresh menu
  if (!result.active) {
    lastTask.value.active = true;
    return setTimeout(refreshTasks, 2000);
  }

  setTimeout(waitForLastTask, 2000);
}

async function refreshTasks() {
  const [error, result] = await taskModel.getByType(TASK_TYPES.TASK_CHECK_CERTS);
  if (error) return console.error(error);

  lastTask.value = result[0] || {};

  // limit to last 10
  taskLogsMenu.value = result.slice(0,10).map(t => {
    return {
      icon: 'fa-solid ' + ((!t.active && t.success) ? 'status-active fa-check-circle' : (t.active ? 'fa-circle-notch fa-spin' : 'status-error fa-times-circle')),
      label: prettyLongDate(t.ts),
      action: () => { window.open(`/logs.html?taskId=${t.id}`); }
    };
  });

  // if last task is currently active, start polling
  if (lastTask.value.active) waitForLastTask();
}

async function onRenew() {
  lastTask.value.active = true;
  lastTask.value.percent = 0;
  lastTask.value.message = 'Queued';

  // always rebuild the nginx configs when triggered via the UI. we assume user is clicking this because something is wrong
  const [error] = await domainsModel.renewCerts({ rebuild: true });
  if (error) return console.error(error);

  await refreshTasks();
}

onMounted(async () => {
  await refreshTasks();
});

</script>

<template>
  <Section :title="$t('domains.renewCerts.title')">
    <template #header-buttons>
      <Button tool secondary :menu="taskLogsMenu" :disabled="!taskLogsMenu.length">{{ $t('main.action.logs') }}</Button>
    </template>

    <div v-html="$t('domains.renewCerts.description')" style="margin-bottom: 12px"></div>

    <div v-if="lastTask.active" style="margin: 12px 0">
      <ProgressBar :value="lastTask.percent" :busy="true" />
      <div>{{ lastTask.message }}</div>
    </div>

    <Button @click="onRenew()" :loading="lastTask.active" :disabled="lastTask.active">{{ $t('domains.renewCerts.renewAllAction') }}</Button>
  </Section>
</template>