<script setup>

import { ref, onMounted } from 'vue';
import { Button, ProgressBar, Dropdown } from 'pankow';
import { prettyLongDate } from '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';
import DashboardModel from '../models/DashboardModel.js';

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

const domains = ref([]);
const newDomain = ref('');
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;

  if (!result.active) {
    if (result.success) {
      const [error] = await dashboardModel.setDomain(newDomain.value);
      if (error) return console.error(error);
      window.location.href = 'https://my.' + newDomain.value;
    } else {
      await refreshTasks();
    }

    return;
  }

  setTimeout(waitForLastTask, 2000);
}

async function refreshTasks() {
  const [error, result] = await taskModel.getByType(TASK_TYPES.TASK_PREPARE_DASHBOARD_LOCATION);
  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 onSubmit() {
  lastTask.value.active = true;
  lastTask.value.percent = 0;
  lastTask.value.message = 'Preparing dashboard domain';

  const [error] = await dashboardModel.prepareDomain({ domain: newDomain.value });
  if (error) return console.error(error);

  await refreshTasks();
}

onMounted(async () => {
  let [error, result] = await domainsModel.list();
  if (error) return console.error(error);

  domains.value = result;

  [error, result] = await dashboardModel.config();
  if (error) return console.error(error);

  newDomain.value = (domains.value.find(d => d.domain === result.adminDomain) || domains.value[0]).domain;

  await refreshTasks();
});

</script>

<template>
  <Section :title="$t('domains.changeDashboardDomain.title')">
    <template #header-buttons>
      <Button tool icon="fa-solid fa-align-left" v-tooltip="$t('domains.renewCerts.showLogsAction')" :menu="taskLogsMenu" :disabled="!taskLogsMenu.length"/>
    </template>

    <p v-html="$t('domains.changeDashboardDomain.description')"></p>

    <div v-if="lastTask.active">
      <ProgressBar :value="lastTask.percent" />
      <div>{{ lastTask.message }}</div>
    </div>

    <Dropdown v-model="newDomain" :options="domains" option-key="domain" option-label="domain" />

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