<script setup>

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

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, TableView, Dialog, Checkbox } from 'pankow';
import { prettyDecimalSize } from 'pankow/utils';
import { eachLimit } from 'async';
import Section from '../components/Section.vue';
import MailboxDialog from '../components/MailboxDialog.vue';
import DomainsModel from '../models/DomainsModel.js';
import MailModel from '../models/MailModel.js';
import GroupsModel from '../models/GroupsModel.js';
import UsersModel from '../models/UsersModel.js';
import MailboxesModel from '../models/MailboxesModel.js';

const domainsModel = DomainsModel.create();
const mailModel = MailModel.create();
const groupsModel = GroupsModel.create();
const mailboxesModel = MailboxesModel.create();
const usersModel = UsersModel.create();

const columns = {
  fullName: { label: t('email.incoming.mailboxes.name'), sort: true },
  ownerDisplayName: { label: t('email.incoming.mailboxes.owner'), sort: true },
  aliases: { label: t('email.incoming.mailboxes.aliases'), sort: true },
  usage: { label: t('email.incoming.mailboxes.usage'), sort: true },
  actions: {}
};

const busy = ref(true);
const mailboxes = ref([]);
const domains = ref([]);
const users = ref([]);
const groups = ref([]);

function renderAliases(aliases) {
  return aliases.map(a => `${a.name}@${a.domain}`).join(', ');
}

const mailboxDialog = useTemplateRef('mailboxDialog');

async function onAddOrEdit(mailbox = null) {
  mailboxDialog.value.open(mailbox);
}

const removeDialog = useTemplateRef('removeDialog');
const removeBusy = ref(false);
const removeError = ref('');
const removePurge = ref(false);
const removeMailbox = ref({});

function onRemove(mailbox) {
  removeBusy.value = false;
  removePurge.value = false;
  removeError.value = '';
  removeMailbox.value = mailbox;

  removeDialog.value.open();
}

async function onSubmitRemove() {
  removeBusy.value = true;
  removeError.value = '';

  const [error] = await mailboxesModel.remove(removeMailbox.value.domain, removeMailbox.value.name, removePurge.value);
  if (error) {
    removeBusy.value = false;
    removeError.value = error.body ? error.body.message : 'Internal error';
    return console.error(error);
  }

  await refresh();
  removeDialog.value.close();

  removeBusy.value = false;
}

async function refresh() {
  busy.value = true;

  let tmp = [];
  async function refreshForDomain(domain) {
    let [error, result] = await mailModel.usage(domain);
    if (error) return console.error(error);

    const usage = result;

    [error, result] = await mailModel.listMailboxes(domain);
    if (error) throw error;

    result.forEach((m) => {
      m.fullName = m.name + '@' + m.domain;

      m.owner = users.value.find(u => u.id === m.ownerId) || null;
      if (!m.owner) m.owner = groups.value.find(g => g.id === m.ownerId) || null;

      m.ownerDisplayName = m.owner ? (m.owner.username || m.owner.name) : '';
      m.usage = usage[m.fullName] || null;
    });

    tmp = tmp.concat(result);
  }

  try {
    await eachLimit(domains.value.map(d => d.domain), 10, refreshForDomain);
  } catch (error) {
    return console.error(error);
  }

  mailboxes.value = tmp;
  busy.value = false;
}

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

  domains.value = result;

  [error, result] = await usersModel.list();
  if (error) return console.error(error);

  users.value = result;

  [error, result] = await groupsModel.list();
  if (error) return console.error(error);

  groups.value = result;

  await refresh();
});

</script>

<template>
  <div>
    <Dialog ref="removeDialog"
      :title="$t('email.deleteMailboxDialog.title', { name: removeMailbox.name, domain: removeMailbox.domain })"
      :confirm-label="$t('email.deleteMailboxDialog.deleteAction')"
      :confirm-busy="removeBusy"
      :confirm-active="!removeBusy"
       confirm-style="danger"
      :reject-label="removeBusy ? '' : $t('main.dialog.cancel')"
       reject-style="secondary"
      @confirm="onSubmitRemove()"
    >
      <div>
        <div class="text-danger" v-if="removeError">{{ removeError }}</div>
        <div v-html="$t('email.deleteMailboxDialog.description')"></div>
        <br/>
        <Checkbox v-model="removePurge" :label="$t('email.deleteMailboxDialog.purgeMailboxCheckbox')" />
      </div>
    </Dialog>

    <MailboxDialog ref="mailboxDialog" :users="users" :groups="groups" :domains="domains" @success="refresh()"/>

    <Section :title="$t('email.incoming.mailboxes.title')">
      <template #header-buttons>
        <Button @click="onAddOrEdit()">{{ $t('email.incoming.mailboxes.addAction') }}</Button>
      </template>

      <TableView :columns="columns" :model="mailboxes" :busy="busy" @row-click="onAddOrEdit">
        <template #aliases="mailbox">{{ renderAliases(mailbox.aliases) }}</template>
        <template #usage="mailbox">
          <span v-if="mailbox.usage">{{ prettyDecimalSize(mailbox.usage.quotaValue)  }} <span ng-show="mailUsage[mailbox.fullName].quotaLimit">/ {{ prettyDecimalSize(mailbox.usage.quotaLimit) }}</span></span>
          <span v-else>{{ $t('main.loadingPlaceholder') }} ...</span>
        </template>
        <template #actions="mailbox">
          <div class="table-actions">
            <Button tool secondary small icon="fa fa-pencil-alt" @click.stop="onAddOrEdit(mailboxe)"></Button>
            <Button tool danger small icon="fa-solid fa-trash-alt" @click.stop="onRemove(mailbox)"></Button>
          </div>
        </template>
      </TableView>
    </Section>
  </div>
</template>
