<script setup>

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

import { ref, onMounted, useTemplateRef, computed, inject } from 'vue';
import { Button, TableView, TextInput, InputDialog, Menu } from '@cloudron/pankow';
import Certificates from '../components/Certificates.vue';
import SyncDns from '../components/SyncDns.vue';
import DomainDialog from '../components/DomainDialog.vue';
import DashboardDomain from '../components/DashboardDomain.vue';
import WellKnownDialog from '../components/WellKnownDialog.vue';
import Section from '../components/Section.vue';
import DashboardModel from '../models/DashboardModel.js';
import DomainsModel from '../models/DomainsModel.js';

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

const busy = ref(false);
const domains = ref([]);
const search = ref('');
const dashboardDomain = ref('');
const domainDialog = useTemplateRef('domainDialog');
const wellKnownDialog = useTemplateRef('wellKnownDialog');

const features = inject('features');
const subscriptionRequiredDialog = inject('subscriptionRequiredDialog');

function onAdd () {
  if (features.value.domainMaxCount <= domains.value.length) subscriptionRequiredDialog.value.open();
  else domainDialog.value.open(null);
}

function onEdit(domain) {
  domainDialog.value.open(domain);
}

const inputDialog = useTemplateRef('inputDialog');

async function onRemove(domain) {
  const yes = await inputDialog.value.confirm({
    message: t('domains.removeDialog.title', { domain: domain.domain }),
    confirmStyle: 'danger',
    confirmLabel: t('domains.removeDialog.removeAction'),
    rejectLabel: t('main.dialog.cancel')
  });

  if (!yes) return;

  const [error] = await domainsModel.remove(domain.domain);
  if (error) {
    if (error.status === 409) window.pankow.notify({ text: error.body.message || `Domain is still in use.`, type: 'danger', persistent: true });
    return console.error(error);
  }

  await refreshDomains();
}

const columns = ref({
  domain: {
    label: t('domains.domain'),
    sort: true
  },
  provider: {
    label: t('domains.provider'),
    sort: true,
    hideMobile: true,
  },
  actions: {
    label: '',
    sort: false
  }
});

const actionMenuModel = ref([]);
const actionMenuElement = useTemplateRef('actionMenuElement');
function onActionMenu(domain, event) {
  actionMenuModel.value = [{
    icon: 'fa-solid fa-pencil-alt',
    label: t('main.action.edit'),
    action: onEdit.bind(null, domain),
  },{
    separator: true,
  }, {
    icon: 'fa-solid fa-atlas',
    label: t('domains.tooltipWellKnown'),
    action: () => wellKnownDialog.value.open(domain),
  }, {
    separator: true,
  }, {
    icon: 'fa-solid fa-trash-alt',
    label: t('main.action.remove'),
    disabled: domain.domain.value === dashboardDomain.value,
    action: onRemove.bind(null, domain),
  }];

  actionMenuElement.value.open(event, event.currentTarget);
}

const filteredDomains = computed(() => {
  if (!search.value) return domains.value;

  return domains.value.filter(d => {
    return d.domain.indexOf(search.value) !== -1 || d.provider.indexOf(search.value) !== -1;
  });
});

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

  domains.value = result;
}

onMounted(async () => {
  busy.value = true;
  await refreshDomains();

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

  dashboardDomain.value = result.adminDomain;
  busy.value = false;
});

</script>

<template>
  <div class="content">
    <Menu ref="actionMenuElement" :model="actionMenuModel" />
    <InputDialog ref="inputDialog" />
    <DomainDialog ref="domainDialog" @success="refreshDomains()"/>
    <WellKnownDialog ref="wellKnownDialog" @success="refreshDomains()"/>

    <Section :title="$t('domains.title')">
      <template #header-buttons>
        <TextInput v-model="search" :placeholder="$t('main.searchPlaceholder')"/>
        <Button @click="onAdd()">{{ $t('main.action.add') }}</Button>
      </template>

      <div>{{ $t('domains.domainDialog.addDescription') }}</div>

      <br/>

      <TableView :model="filteredDomains" :columns="columns" :busy="busy" style="max-height: 200px;">
        <template #provider="domain">
          {{ DomainsModel.prettyProviderName(domain.provider) }}
        </template>
        <template #actions="domain">
          <div style="text-align: right;">
            <Button tool plain secondary @click.capture="onActionMenu(domain, $event)" icon="fa-solid fa-ellipsis" />
          </div>
        </template>
      </TableView>
    </Section>

    <Certificates />
    <SyncDns />
    <DashboardDomain />
  </div>
</template>