<script setup>

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

import { ref, onMounted, useTemplateRef, inject, computed } from 'vue';
import { Button, TableView, Dialog, Checkbox, TextInput, Menu } from '@cloudron/pankow';
import { prettyDecimalSize } from '@cloudron/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,
    hideMobile: true,
  },
  aliases: {
    label: t('email.incoming.mailboxes.aliases'),
    sort: true,
    hideMobile: true,
  },
  usage: {
    label: t('email.incoming.mailboxes.usage'),
    sort: true,
    hideMobile: true,
  },
  quota: {
    label: 'Quota',
    sort: true,
    hideMobile: true,
  },
  actions: {}
};

const actionMenuModel = ref([]);
const actionMenuElement = useTemplateRef('actionMenuElement');
function onActionMenu(mailbox, event) {
  actionMenuModel.value = [{
    icon: 'fa-solid fa-pencil-alt',
    label: t('main.action.edit'),
    action: onAddOrEdit.bind(null, mailbox),
  }, {
    separator: true,
  }, {
    icon: 'fa-solid fa-trash-alt',
    label: t('main.action.remove'),
    action: onRemove.bind(null, mailbox),
  }];

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

const busy = ref(true);
const mailboxes = ref([]);
const mailboxesUsage = ref(0);
const domains = ref([]);
const users = ref([]);
const groups = ref([]);
const searchFilter = ref('');

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

const filteredMailboxes = computed(() => {
  if (!searchFilter.value) return mailboxes.value;

  return mailboxes.value.filter(m => {
    const search = searchFilter.value.toLowerCase();

    if (m.fullName.toLowerCase().indexOf(search) !== -1) return true;
    if (m.ownerId.indexOf(search) !== -1) return true;
    if (m.ownerDisplayName.indexOf(search) !== -1) return true;
    if (m.aliases.find(a => a.domain.toLowerCase().indexOf(search) !== -1 || a.name.toLowerCase().indexOf(search) !== -1)) return true;

    return false;
  });
});

const filteredMailboxesUsage = computed(() => {
  return filteredMailboxes.value.reduce((acc, m) => acc + (m.usage && m.usage.diskSize), 0);
});

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

const mailboxDialog = useTemplateRef('mailboxDialog');

async function onAddOrEdit(mailbox = null) {
  if (mailbox || features.value.mailboxMaxCount > mailboxes.value.length) mailboxDialog.value.open(mailbox);
  else subscriptionRequiredDialog.value.open();
}

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() {
  let tmp = [];
  async function refreshForDomain(domain) {
    let [error, result] = await mailModel.usage(domain);
    // retry if mail addon cannot be reached during restarts
    if (error && error.status === 424) return setTimeout(refresh, 2000);
    else if (error) return console.error(error);

    const usage = result;

    [error, result] = await mailboxesModel.list(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;
  mailboxesUsage.value = mailboxes.value.reduce((acc, m) => acc + (m.usage && m.usage.diskSize), 0);
}

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

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

  busy.value = false;
});

</script>

<template>
  <div class="content">
    <Menu ref="actionMenuElement" :model="actionMenuModel" />
    <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-title-extra>
        <span style="font-weight: normal; font-size: 14px">({{ $t('emails.domains.stats', { mailboxCount: filteredMailboxes.length, usage: prettyDecimalSize(filteredMailboxesUsage) }) }})</span>
      </template>
      <template #header-buttons>
        <TextInput :placeholder="$t('main.searchPlaceholder')" style="flex-grow: 1;" v-model="searchFilter"/>
        <Button @click="onAddOrEdit()">{{ $t('email.incoming.mailboxes.addAction') }}</Button>
      </template>

      <TableView :columns="columns" :model="filteredMailboxes" :busy="busy" :placeholder="$t('email.incoming.mailboxes.emptyPlaceholder')">
        <template #aliases="mailbox">{{ renderAliases(mailbox.aliases) }}</template>
        <template #usage="mailbox">
          <span v-if="mailbox.usage">{{ prettyDecimalSize(mailbox.usage.diskSize)  }}</span>
          <span v-else>{{ $t('main.loadingPlaceholder') }} ...</span>
        </template>
        <template #quota="mailbox">
          <span v-if="mailbox.usage && mailbox.usage.quotaLimit">{{ prettyDecimalSize(mailbox.usage.quotaLimit) }}</span>
        </template>
        <template #actions="mailbox">
          <div style="text-align: right;">
            <Button tool plain secondary @click.capture="onActionMenu(mailbox, $event)" icon="fa-solid fa-ellipsis" />
          </div>
        </template>
      </TableView>

    </Section>
  </div>
</template>
