<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 tasksModel = TasksModel.create();
const domainsModel = DomainsModel.create();

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

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

  const [error, result] = await tasksModel.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 tasksModel.getByType(TASK_TYPES.TASK_SYNC_DNS_RECORDS);
  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 onSync() {
  lastTask.value.active = true;
  lastTask.value.percent = 0;
  lastTask.value.message = 'Queued';

  // no options means all records
  const [error] = await domainsModel.setDnsRecords({});
  if (error) return console.error(error);

  await refreshTasks();
}

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

</script>

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

    <div v-html="$t('domains.syncDns.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="onSync()" :loading="lastTask.active" :disabled="lastTask.active">{{ $t('domains.syncDns.syncAction') }}</Button>
  </Section>
</template>