<script setup>

import { ref, useTemplateRef } from 'vue';
import { Dialog, TextInput, FormGroup } from '@cloudron/pankow';
import DomainsModel from '../models/DomainsModel.js';

const emit = defineEmits([ 'success' ]);

const domainsModel = DomainsModel.create();

const dialog = useTemplateRef('dialog');
const busy = ref(false);
const errorMessage = ref('');
const domain = ref('');
const matrixHostname = ref('');
const mastodonHostname = ref('');
const jitsiHostname = ref('');
const carddavLocation = ref('');
const caldavLocation = ref('');

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

  const wellKnown = {};

  if (matrixHostname.value) {
    wellKnown['matrix/server'] = JSON.stringify({ 'm.server': matrixHostname.value });
    // https://matrix.org/docs/spec/client_server/latest#get-well-known-matrix-client
    wellKnown['matrix/client'] = JSON.stringify({
      'm.homeserver': {
        'base_url': 'https://' + matrixHostname.value
      },
      'im.vector.riot.jitsi': {
        'preferredDomain': jitsiHostname.value
      }
    });
  } else if (jitsiHostname.value) { // only if matrixHostname is not set
    wellKnown['matrix/client'] = JSON.stringify({
      'im.vector.riot.jitsi': {
        'preferredDomain': jitsiHostname.value
      }
    });
  }

  if (mastodonHostname.value) {
    wellKnown['host-meta'] = '<?xml version="1.0" encoding="UTF-8"?>\n'
      + '<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n'
      + '<Link rel="lrdd" type="application/xrd+xml" template="https://' + mastodonHostname.value + '/.well-known/webfinger?resource={uri}"/>\n'
      + '</XRD>';
  }

  if (carddavLocation.value) wellKnown['carddav'] = carddavLocation.value;
  if (caldavLocation.value) wellKnown['caldav'] = caldavLocation.value;

  const [error] = await domainsModel.setWellKnown(domain.value, wellKnown);
  if (error) {
    errorMessage.value = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  emit('success');
  dialog.value.close();
}

defineExpose({
  open(d) {
    busy.value = false;
    errorMessage.value = '';
    domain.value = d.domain;
    matrixHostname.value = '';
    mastodonHostname.value = '';
    jitsiHostname.value = '';
    caldavLocation.value = '';
    carddavLocation.value = '';

    try {
      if (d.wellKnown) {
        if (d.wellKnown['matrix/server']) matrixHostname.value = JSON.parse(d.wellKnown['matrix/server'])['m.server'];
        if (d.wellKnown['host-meta']) mastodonHostname.value = d.wellKnown['host-meta'].match(new RegExp('template="https://(.*?)/'))[1];
        if (d.wellKnown['matrix/client']) {
          const parsed = JSON.parse(d.wellKnown['matrix/client']);
          if (parsed['im.vector.riot.jitsi'] && parsed['im.vector.riot.jitsi']['preferredDomain']) {
            jitsiHostname.value = parsed['im.vector.riot.jitsi']['preferredDomain'];
          }
        }
        if (d.wellKnown['carddav']) carddavLocation.value = d.wellKnown['carddav'];
        if (d.wellKnown['caldav']) caldavLocation.value = d.wellKnown['caldav'];
      }
    } catch (e) {
      console.error(e);
    }

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

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('domains.wellknown.title')"
    :confirm-busy="busy"
    :confirm-label="$t('main.dialog.save')"
    :reject-label="$t('main.dialog.cancel')"
    :reject-active="!busy"
     reject-style="secondary"
    @confirm="onSubmit()"
  >
    <div v-html="$t('domains.wellknown.context', { domain })"></div>
    <br/>
    <div v-html="$t('domains.wellknown.description', { domain, docsLink: 'https://docs.cloudron.io/domains/#well-known-locations' })"></div>

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

        <p class="has-error" v-show="errorMessage">{{ errorMessage }}</p>

        <FormGroup>
          <label for="">{{ $t('domains.domainDialog.carddavLocation') }}</label>
          <TextInput id="" v-model="carddavLocation" placeholder="contacts.example.com"/>
        </FormGroup>

        <FormGroup>
          <label for="">{{ $t('domains.domainDialog.caldavLocation') }}</label>
          <TextInput id="" v-model="caldavLocation" placeholder="calendar.example.com"/>
        </FormGroup>

        <FormGroup>
          <label for="">{{ $t('domains.domainDialog.matrixHostname') }}</label>
          <TextInput id="" v-model="matrixHostname" placeholder="synapse.example.com:443"/>
        </FormGroup>

        <FormGroup>
          <label for="">{{ $t('domains.domainDialog.mastodonHostname') }}</label>
          <TextInput id="" v-model="mastodonHostname" placeholder="mastodon.example.com"/>
        </FormGroup>

        <FormGroup>
          <label for="">{{ $t('domains.domainDialog.jitsiHostname') }}</label>
          <TextInput id="" v-model="jitsiHostname" placeholder="jitsi.example.com"/>
        </FormGroup>
      </fieldset>
    </form>
  </Dialog>
</template>
