<script setup>

const props = defineProps([ 'app' ]);

import { ref, onMounted } from 'vue';
import { Button, Radiobutton, InputGroup, FormGroup, TextInput, SingleSelect } from '@cloudron/pankow';
import { ISTATES } from '../../constants.js';
import AppsModel from '../../models/AppsModel.js';
import DomainsModel from '../../models/DomainsModel.js';
import MailboxesModel from '../../models/MailboxesModel.js';

const appsModel = AppsModel.create();
const domainsModel = DomainsModel.create();
const mailboxesModel = MailboxesModel.create();

const domains = ref([]);
const mailboxes = ref([]);

const hasRecvmail = ref(false);
const hasSendmail = ref(false);
const sendmailBusy = ref(false);
const sendmailError = ref('');
const sendmailSupportsDisplayName = ref(false);
const sendmailOptional = ref(false);
const sendmailMailboxName = ref('');
const sendmailDisplayName = ref('');
const sendmailDomain = ref('');
const enableMailbox = ref(0);

const recvmailBusy = ref(false);
const recvmailError = ref('');
const recvmailEnable = ref(0);
const recvmailMailbox = ref({});

async function onSendmailSubmit() {
  if (!sendmailMailboxName.value) return;

  sendmailBusy.value = true;
  sendmailError.value = '';

  const data = {
    enable: !!enableMailbox.value
  };

  if (data.enable) {
    data.mailboxName = sendmailMailboxName.value;
    data.mailboxDomain = sendmailDomain.value;
    data.mailboxDisplayName = sendmailDisplayName.value;
  }

  const [error] = await appsModel.configure(props.app.id, 'mailbox', data);
  if (error) {
    sendmailError.value = error.body ? error.body.message : 'Internal error';
    sendmailBusy.value = false;
    return console.error(error);
  }

  sendmailBusy.value = false;
}

async function onRecvmailSubmit() {
  recvmailBusy.value = true;
  recvmailError.value = '';

  const data = {
    enable: !!recvmailEnable.value
  };

  if (data.enable) {
    data.inboxName = recvmailMailbox.value.split('@')[0];
    data.inboxDomain = recvmailMailbox.value.split('@')[1];
  }

  const [error] = await appsModel.configure(props.app.id, 'inbox', data);
  if (error) {
    recvmailError.value = error.body ? error.body.message : 'Internal error';
    recvmailBusy.value = false;
    return console.error(error);
  }

  recvmailBusy.value = false;
}

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

  domains.value = result.map(d => {
    return {
      id: d.domain,
      label: `@${d.domain}`,
      domain: d.domain
    };
  });

  sendmailSupportsDisplayName.value = props.app.manifest?.addons?.sendmail?.supportsDisplayName;
  sendmailOptional.value = props.app.manifest?.addons?.sendmail?.optional;
  sendmailMailboxName.value = props.app.mailboxName || '';
  sendmailDisplayName.value = props.app.mailboxDisplayName || '';
  sendmailDomain.value = props.app.mailboxDomain || props.app.domain;
  enableMailbox.value = props.app.enableMailbox ? 1 : 0;

  let tmp = [];
  for (const d of domains.value) {
    const [error, result] = await mailboxesModel.list(d.domain);
    if (error) return console.error(error);
    tmp = tmp.concat(result);
  }

  mailboxes.value = tmp.map(m => {
    return {
      id: m.name + '@' + m.domain,
      label: m.name + '@' + m.domain,
    };
  });

  recvmailEnable.value = props.app.enableInbox ? 1 : 0;
  recvmailMailbox.value = props.app.inboxName ? props.app.inboxName + '@' + props.app.inboxDomain : '';

  // do this last to avoid ui flicker
  hasRecvmail.value = props.app.manifest?.addons?.recvmail;
  hasSendmail.value = props.app.manifest?.addons?.sendmail;
});

</script>

<template>
  <div>
    <div v-if="hasSendmail">
      <FormGroup>
        <label>{{ $t('app.email.configuration.title') }} <sup><a href="https://docs.cloudron.io/apps/#mail-from-address" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>

        <Radiobutton v-if="sendmailOptional" v-model="enableMailbox" :value="1" :label="$t('app.email.from.enable')"/>

        <div style="margin-bottom: 12px;" :style="{ 'padding-left': sendmailOptional ? '25px' : '0' }">
          <div v-html="$t('app.email.from.enableDescription', { domain: app.domain, domainConfigLink: ('/#/email-domain/' + app.domain) })"></div>

          <form @submit.prevent="onSendmailSubmit()" autocomplete="off">
            <fieldset :disabled="enableMailbox === 0 || sendmailBusy || (app.error && app.error.installationState !== ISTATES.PENDING_SERVICES_CHANGE) || app.taskId">
              <input type="submit" style="display: none;" :disabled="!sendmailMailboxName"/>

              <FormGroup>
                <div class="has-error" v-if="sendmailError">{{ sendmailError }}</div>

                <label>{{ $t('app.email.from.title') }}</label>
                <div style="display: flex; gap: 10px;">
                  <TextInput v-if="sendmailSupportsDisplayName" v-model="sendmailDisplayName" :placeholder="$t('app.email.from.displayName')"/>
                  <InputGroup>
                    <TextInput v-model="sendmailMailboxName" :placeholder="$t('app.email.from.mailboxPlaceholder')"/>
                    <SingleSelect v-model="sendmailDomain" :disabled="!enableMailbox" :options="domains" option-key="id"/>
                  </InputGroup>
                </div>
              </FormGroup>
            </fieldset>
          </form>
        </div>

        <Radiobutton v-if="sendmailOptional" v-model="enableMailbox" :value="0" :label="$t('app.email.from.disable')"/>
        <div v-if="sendmailOptional" style="padding-left: 25px;">{{ $t('app.email.from.disableDescription') }}</div>
      </FormGroup>

      <br v-if="sendmailOptional"/>
      <Button @click="onSendmailSubmit()" :loading="sendmailBusy" :disabled="sendmailBusy || (app.error && app.error.installationState !== ISTATES.PENDING_SERVICES_CHANGE) || app.taskId">{{ $t('app.email.from.saveAction') }}</Button>
    </div>

    <hr style="margin-top: 20px" v-if="hasSendmail && hasRecvmail"/>

    <div v-if="hasRecvmail">
      <FormGroup>
        <label>{{ $t('app.email.inbox.title') }} <sup><a href="https://docs.cloudron.io/apps/#inbox" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>

        <Radiobutton v-model="recvmailEnable" :value="1" :label="$t('app.email.inbox.enable')"/>
        <div style="margin-bottom: 18px; padding-left: 25px">
          <div v-html="$t('app.email.inbox.enableDescription', { domain: app.domain, domainConfigLink: ('/#/email/' + app.domain) })"></div>

          <div style="margin-top: 15px">
            <SingleSelect v-model="recvmailMailbox" :disabled="!recvmailEnable" :options="mailboxes" option-key="id"/>
            <div class="has-error" v-if="recvmailError">{{ recvmailError }}</div>
          </div>
        </div>

        <Radiobutton v-model="recvmailEnable" :value="0" :label="$t('app.email.inbox.disable')"/>
        <div style="padding-left: 25px;">{{ $t('app.email.inbox.disableDescription') }}</div>
      </FormGroup>

      <br/>
      <Button @click="onRecvmailSubmit()" :disabled="recvmailBusy || (app.error && app.error.installationState !== ISTATES.PENDING_SERVICES_CHANGE) || app.taskId" :loading="recvmailBusy">{{ $t('app.email.from.saveAction') }}</Button>
    </div>
  </div>
</template>
