<script setup>

import { ref, useTemplateRef } from 'vue';
import { Dialog, Button, TextInput, FormGroup, Checkbox, InputGroup, SingleSelect } from 'pankow';
import { prettyDecimalSize } from 'pankow/utils';
import MailboxesModel from '../models/MailboxesModel.js';

const emit = defineEmits([ 'success' ]);
const props = defineProps([ 'users', 'groups', 'domains' ]);

const mailboxesModel = MailboxesModel.create();

const dialog = useTemplateRef('dialog');
const busy = ref(false);
const formError = ref('');
const name = ref('');
const domain = ref('');
const mailbox = ref(null);
const aliases = ref([]);
const ownerId = ref('');
const usersAndGroups = ref([]);
const storageQuotaEnabled = ref(false);
const storageQuotaTicks = [ 500*1000*1000, 5*1000*1000*1000, 15*1000*1000*1000, 50*1000*1000*1000, 100*1000*1000*1000 ];
const storageQuota = ref(0);
const active = ref(false);
const enablePop3 = ref(false);

function onAddAlias() {
  aliases.value.push({
    name: '',
    domain: props.domains[0].domain,
  });
}

async function onRemoveAlias(index) {
  aliases.value.splice(index, 1);
}

async function onSubmit() {
  busy.value = true;
  formError.value = '';

  const data = {
    ownerId: ownerId.value,
    ownerType: ownerId.value.indexOf('gid-') === 0 ? 'group' : 'user',
    active: active.value,
    enablePop3: enablePop3.value,
    storageQuota: storageQuotaEnabled.value ? parseInt(storageQuota.value) : 0,
    messagesQuota: 0
  };

  if (mailbox.value) {
    let [error] = await mailboxesModel.update(domain.value, name.value, data);
    if (error) {
      busy.value = false;
      formError.value = error.body ? error.body.message : 'Internal error';
      return console.error(error);
    }

    [error] = await mailboxesModel.setAliases(domain.value, name.value, aliases.value);
    if (error) {
      busy.value = false;
      formError.value = error.body ? error.body.message : 'Internal error';
      return console.error(error);
    }
  } else {
    const [error] = await mailboxesModel.add(domain.value, name.value, data);
    if (error) {
      busy.value = false;
      formError.value = error.body ? error.body.message : 'Internal error';
      return console.error(error);
    }
  }

  emit('success');
  dialog.value.close();
  busy.value = false;
}

defineExpose({
  async open(m = null) {
    busy.value = false;
    formError.value = '';
    mailbox.value = m;

    name.value = m ? m.name : '';
    domain.value = m ? m.domain : '';
    ownerId.value = m ? m.ownerId : '';
    aliases.value = m ? JSON.parse(JSON.stringify(m.aliases)) : [];
    active.value = m ? m.active : true;
    enablePop3.value = m ? m.enablePop3 : false;

    usersAndGroups.value = props.users.concat(props.groups);

    // unify on .name for multiselect
    usersAndGroups.value.forEach(u => {
      u.name = u.name || u.username;
    });

    dialog.value.open();
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="mailbox ? $t('email.editMailboxDialog.title', { name: mailbox.name, domain: mailbox.domain }) : $t('email.addMailboxDialog.title')"
    :confirm-label="$t(mailbox ? 'main.dialog.save' : 'email.incoming.mailboxes.addAction')"
    :confirm-busy="busy"
    :confirm-active="!busy && name !== '' && domain !== ''"
     reject-style="secondary"
    :reject-label="busy ? null : $t('main.dialog.cancel')"
    @confirm="onSubmit()"
  >
    <div>
      <div class="has-error" v-if="formError">{{ formError }}</div>

      <form @submit.prevent="onSubmit()" novalidate autocomplete="off">
         <fieldset :disabled="busy">
          <input type="submit" style="display: none;" :disabled="!name || !domain"/>

          <FormGroup v-if="!mailbox">
            <label for="nameInput">{{ $t('email.addMailboxDialog.name') }}</label>
            <InputGroup>
              <TextInput id="nameInput" style="flex-grow: 1;" v-model="name"/>
              <SingleSelect v-model="domain" :options="domains" option-key="domain" option-label="domain" />
            </InputGroup>
          </FormGroup>

          <FormGroup>
            <label>{{ $t('email.editMailboxDialog.owner') }}</label>
            <SingleSelect v-model="ownerId" :options="usersAndGroups" option-key="id" option-label="name"/>
          </FormGroup>

          <Checkbox v-model="active" :label="$t('email.updateMailboxDialog.activeCheckbox')"/><br/>

          <Checkbox v-model="enablePop3" :label="$t('email.updateMailboxDialog.enablePop3')"/><br/>

          <FormGroup>
            <div>
              <Checkbox v-model="storageQuotaEnabled" :label="$t('email.editMailboxDialog.enableStorageQuota')"/>
              <b v-if="storageQuotaEnabled">: {{ prettyDecimalSize(storageQuota) }}</b>
            </div>
            <input type="range" id="storageQuota" :disabled="!storageQuotaEnabled" v-model="storageQuota" step="500000000" :min="storageQuotaTicks[0]" :max="storageQuotaTicks[storageQuotaTicks.length-1]" list="storageQuotaTicks" />
            <datalist id="storageQuotaTicks">
              <option v-for="quota in storageQuotaTicks" :value="quota" :key="quota"></option>
            </datalist>
          </FormGroup>

          <!-- we only show this on edit for now as it is a separate REST call which may fail after the mailbox was added -->
          <FormGroup v-if="mailbox">
            <label>{{ $t('email.editMailboxDialog.aliases') }}</label>
            <div v-for="(alias, index) in aliases" :key="alias" style="margin-bottom: 10px;">
              <InputGroup>
                <TextInput style="flex-grow: 1;" v-model="alias.name"/>
                <SingleSelect v-model="alias.domain" :options="domains" option-key="domain" option-label="domain" />
                <Button tool danger icon="fa-solid fa-trash-alt" @click="onRemoveAlias(index)"/>
              </InputGroup>
            </div>
            <div v-if="aliases.length === 0">
              {{ $t('email.editMailboxDialog.noAliases') }} <span class="actionable" @click="onAddAlias($event)">{{ $t('email.editMailboxDialog.addAliasAction') }}</span>
            </div>
            <div v-else>
              <div class="actionable" @click="onAddAlias($event)">{{ $t('email.editMailboxDialog.addAnotherAliasAction') }}</div>
            </div>
          </FormGroup>
        </fieldset>
      </form>
    </div>
  </Dialog>
</template>