<script setup>

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;

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

import { ref, onMounted, useTemplateRef, computed } from 'vue';
import { Button, ButtonGroup, TableView, TextInput, InputDialog } from '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(API_ORIGIN, localStorage.token);
const domainsModel = DomainsModel.create(API_ORIGIN, localStorage.token);

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

function prettyProviderName(domain) {
  switch (domain.provider) {
    case 'bunny': return 'Bunny';
    case 'route53': return 'AWS Route53';
    case 'cloudflare': return 'Cloudflare';
    case 'desec': return 'deSEC';
    case 'digitalocean': return 'DigitalOcean';
    case 'dnsimple': return 'dnsimple';
    case 'gandi': return 'Gandi LiveDNS';
    case 'hetzner': return 'Hetzner DNS';
    case 'inwx': return 'INWX';
    case 'linode': return 'Linode';
    case 'namecom': return 'Name.com';
    case 'namecheap': return 'Namecheap';
    case 'netcup': return 'Netcup';
    case 'ovh': return 'OVH';
    case 'gcdns': return 'Google Cloud';
    case 'godaddy': return 'GoDaddy';
    case 'vultr': return 'Vultr';
    case 'manual': return 'Manual';
    case 'porkbun': return 'Porkbun';
    case 'wildcard': return 'Wildcard';
    case 'noop': return 'No-op';
    default: return 'Unknown';
  }
};

function onAdd () {
  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: `Domain ${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
  },
  actions: {
    label: '',
    sort: false
  }
});

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 () => {
  await refreshDomains();

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

  dashboardDomain.value = result.adminDomain;
});

</script>

<template>
  <div class="content">
    <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()" icon="fa-solid fa-plus"> {{ $t('domains.addDomain') }}</Button>
      </template>

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

      <TableView :model="filteredDomains" :columns="columns" style="max-height: 200px;" @row-click="onEdit" :hover="false">
        <template #provider="domain">
          {{ prettyProviderName(domain) }}
        </template>
        <template #actions="domain">
          <div class="table-actions">
            <ButtonGroup>
              <Button tool outline small secondary @click.stop="wellKnownDialog.open(domain)" v-tooltip="$t('domains.tooltipWellKnown')" icon="fa-solid fa-atlas" />
              <Button tool outline small secondary @click.stop="onEdit(domain)" v-tooltip="$t('domains.tooltipEdit')" icon="fa-solid fa-pencil-alt" />
            </ButtonGroup>
            <Button tool outline small danger @click.stop="onRemove(domain)" v-tooltip="$t('domains.tooltipRemove')" :disabled="domain.domain === dashboardDomain" icon="fa-solid fa-trash-alt" />
          </div>
        </template>
      </TableView>
    </Section>

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