<script setup>

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

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

const mailboxesModel = MailboxesModel.create();

const dashboardDomain = inject('dashboardDomain');
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 usersAndGroupsAndApps = 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(5*1000*1000*1000);
const active = ref(false);
const enablePop3 = ref(false);
const domainList = ref([]);

const domainHasIncomingEnabled = computed(() => {
  const selected = domainList.value.find(d => d.domain === domain.value);
  return selected ? selected.enabled : false;
});

function onAddAlias() {
  aliases.value.push({
    name: '',
    domain: domain.value,
    label: '@' + domain.value,
  });
}

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

const form = useTemplateRef('form');
const isFormValid = ref(false);
function validateForm() {
  isFormValid.value = form.value ? form.value.checkValidity() : false;
}

async function onSubmit() {
  if (!form.value.reportValidity()) return;

  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', { domain: domain.value, name: name.value, fullName: name.value + '@' + domain.value });
  dialog.value.close();
  busy.value = false;
}

defineExpose({
  async open(m = null) {
    m = m ? JSON.parse(JSON.stringify(m)) : null; // make a copy
    busy.value = false;
    formError.value = '';
    mailbox.value = m;

    name.value = m ? m.name : '';
    domain.value = m ? m.domain : dashboardDomain.value;
    ownerId.value = m ? m.ownerId : '';
    aliases.value = m ? m.aliases : [];
    active.value = m ? m.active : true;
    enablePop3.value = m ? m.enablePop3 : false;
    storageQuotaEnabled.value = m && m.storageQuota ? true : false;
    storageQuota.value = m && m.storageQuota ? m.storageQuota : 5*1000*1000*1000;
    usersAndGroupsAndApps.value = [];

    if (props.users.length) usersAndGroupsAndApps.value.push({ separator: true, label: 'Users' });
    usersAndGroupsAndApps.value = usersAndGroupsAndApps.value.concat(props.users.map(u => {
      return { ...u, icon: 'fa-solid fa-user', name: u.username || u.displayName || u.email };
    }));

    if (props.groups.length) usersAndGroupsAndApps.value.push({ separator: true, label: 'Groups' });
    usersAndGroupsAndApps.value = usersAndGroupsAndApps.value.concat(props.groups.map(g => {
      return { ...g, icon: 'fa-solid fa-users' };
    }));

    if (props.apps.length) usersAndGroupsAndApps.value.push({ separator: true, label: 'Apps' });
    usersAndGroupsAndApps.value = usersAndGroupsAndApps.value.concat(props.apps.map(a => {
      return { ...a, icon: 'fa-solid fa-cube', name: a.label || a.fqdn };
    }));

    domainList.value = props.domains.map(d => {
      return {
        domain: d.domain,
        label: '@' + d.domain,
        enabled: !!d.enabled,
      };
    });

    dialog.value.open();

    setTimeout(validateForm, 100); // update state of the confirm button
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="mailbox ? $t('email.editMailboxDialog.title') : $t('email.addMailboxDialog.title')"
    :confirm-label="$t(mailbox ? 'main.dialog.save' : 'email.incoming.mailboxes.addAction')"
    :confirm-busy="busy"
    :confirm-active="!busy && isFormValid"
     reject-style="secondary"
    :reject-label="$t('main.dialog.cancel')"
    :reject-active="!busy"
    @confirm="onSubmit()"
  >
    <div>
      <form @submit.prevent="onSubmit()" novalidate autocomplete="off" ref="form" @input="validateForm()">
         <fieldset :disabled="busy">
          <input type="submit" style="display: none;" :disabled="!name || !domain"/>

          <FormGroup>
            <label for="nameInput">{{ $t('email.addMailboxDialog.name') }}</label>
            <InputGroup>
              <TextInput id="nameInput" style="flex-grow: 1;" v-model="name" :readonly="!!mailbox" :required="!mailbox"/>
              <SingleSelect v-model="domain" :options="domainList" option-key="domain" option-label="label" :disabled="!!mailbox" :required="!mailbox"/>
            </InputGroup>
            <div class="warning-label" v-if="!domainHasIncomingEnabled">{{ $t('email.addMailboxDialog.incomingDisabledWarning') }}</div>
            <div class="error-label" v-if="formError">{{ formError }}</div>
          </FormGroup>

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

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

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

          <Checkbox v-model="storageQuotaEnabled" :label="$t('email.editMailboxDialog.enableStorageQuota') + (storageQuotaEnabled ? ` : ${prettyDecimalSize(storageQuota)}` : '')"/>
          <div>
            <input style="width: 100%;" 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>
          </div>

          <!-- 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: 5px 0;">
              <InputGroup>
                <TextInput style="flex-grow: 1;" v-model="alias.name"/>
                <SingleSelect v-model="alias.domain" :options="domainList" option-key="domain" option-label="label" />
                <Button tool danger icon="fa-solid fa-trash-alt" @click="onRemoveAlias(index)"/>
              </InputGroup>
            </div>
            <div style="margin-top: 5px"></div>
            <div v-if="aliases.length === 0">
              {{ $t('email.editMailboxDialog.noAliases') }} <span class="actionable" @click="onAddAlias">{{ $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>