<script setup>

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

import { ref, onMounted, inject } 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 DashboardModel from '../models/DashboardModel.js';
import DomainsModel from '../models/DomainsModel.js';

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

const inputDialog = inject('inputDialog');

const domains = ref([]);
const formError = ref('');
const originalDomain = 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() {
  const confirm = await inputDialog.value.confirm({
    title: t('domains.changeDashboardDomain.confirmTitle'),
    message: t('domains.changeDashboardDomain.confirmMessage'),
    confirmStyle: 'danger',
    confirmLabel: t('main.dialog.yes'),
    rejectLabel: t('main.dialog.cancel'),
    rejectStyle: 'secondary',
  });
  if (!confirm) return;

  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();
}

async function selectCurrentDomain(newDomains) {
  domains.value = newDomains;

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

  if (domains.value.length) {
    const adminDomain = domains.value.find(d => d.domain === result.adminDomain);
    if (adminDomain) {
      newDomain.value = adminDomain.domain;
      originalDomain.value = adminDomain.domain;
    }
  }
}

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

  await selectCurrentDomain(result);

  await refreshTasks();
});

defineExpose({ updateDomains: selectCurrentDomain });

</script>

<template>
  <Section :title="$t('domains.changeDashboardDomain.title')">
    <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">
      <ProgressBar :value="lastTask.percent" :busy="true" />
      <div>{{ lastTask.message }}</div>
    </div>
  </Section>
</template>