<script setup>

import { ref, onMounted } from 'vue';
import { Button, ProgressBar, SingleSelect, InputGroup, TextInput } 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 MailModel from '../models/MailModel.js';

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

const formError = ref('');
const domains = ref([]);
const lastTask = ref({});
const taskLogsMenu = ref([]);
const originalDomain = ref('');
const originalSubdomain = ref('');
const subdomain = ref('');
const domain = ref('');
const busy = ref(false);

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

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

  lastTask.value = result;

  if (!result.active) {
    if (result.success) {
      originalDomain.value = domain.value;
      originalSubdomain.value = subdomain.value;
      busy.value = false;
    } else {
      await refreshTasks();
    }

    return;
  }

  setTimeout(waitForLastTask, 2000);
}

async function refreshTasks() {
  const [error, result] = await taskModel.getByType(TASK_TYPES.TASK_CHANGE_MAIL_LOCATION);
  if (error) return window.cloudron.onError(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 = '';
  busy.value = true;

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

  const [error] = await mailModel.setLocation(subdomain.value, domain.value);
  if (error) return window.cloudron.onError(error);

  originalDomain.value = domain.value;
  originalSubdomain.value = subdomain.value;

  await refreshTasks();
}

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

  domains.value = result;

  [error, result] = await mailModel.location();
  if (error) return window.cloudron.onError(error);

  domain.value = result.domain;
  subdomain.value = result.subdomain;
  originalDomain.value = result.domain;
  originalSubdomain.value = result.subdomain;

  await refreshTasks();
});

</script>

<template>
  <Section :title="$t('emails.settings.location')">
    <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; width: 100%">
        <div v-html="$t('emails.changeDomainDialog.description')"></div>
      </div>
      <form @submit.prevent="onSubmit()" style="display: flex; align-items: center; width: 100%; justify-content: end;" autocomplete="off">
        <input type="submit" style="display: none" :disabled="busy || (originalSubdomain === subdomain && originalDomain === domain)"/>

        <InputGroup style="overflow: hidden;">
          <TextInput v-model="subdomain" :disabled="busy" style="width: 120px"/>
          <SingleSelect v-model="domain" :options="domains" option-key="domain" option-label="domain" :disabled="busy"/>
          <Button tool @click="onSubmit()" :disabled="busy || (originalSubdomain === subdomain && originalDomain === domain)">{{ $t('emails.changeDomainDialog.setAction') }}</Button>
        </InputGroup>
      </form>
    </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>
