<script setup>

import { ref, onMounted } from 'vue';
import { Button, ProgressBar, SingleSelect, InputGroup } from '@cloudron/pankow';
import { prettyLongDate } from '@cloudron/pankow/utils';
import { TASK_TYPES } from '../constants.js';
import Section from '../components/Section.vue';
import SettingsItem from '../components/SettingsItem.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 formError = ref('');
const originalDomain = ref('');
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() {
  formError.value = '';

  lastTask.value.active = true;
  lastTask.value.percent = 0;
  lastTask.value.message = 'Preparing dashboard domain';

  const [error] = await dashboardModel.prepareDomain(newDomain.value);
  if (error) {
    formError.value = error.body ? error.body.message : 'Internal error';
    lastTask.value = {};
    return;
  }

  originalDomain.value = newDomain.value;

  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;
  originalDomain.value = (domains.value.find(d => d.domain === result.adminDomain) || domains.value[0]).domain;

  await refreshTasks();
});

</script>

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

    <SettingsItem wrap>
      <div style="display: flex; align-items: center">
        <div v-html="$t('domains.changeDashboardDomain.description')"></div>
      </div>
      <div style="display: flex; align-items: center">
        <InputGroup>
          <SingleSelect v-model="newDomain" :disabled="lastTask.active" :options="domains" option-key="domain" option-label="domain" @select="formError = ''"/>
          <Button @click="onSubmit()" :loading="lastTask.active" :disabled="lastTask.active || originalDomain === newDomain">{{ $t('domains.changeDashboardDomain.changeAction') }}</Button>
        </InputGroup>
      </div>
    </SettingsItem>

    <div class="error-label" v-if="formError">{{ formError }}</div>

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