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

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>';
  }

  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 = '';

    try {
      if (d.wellKnown && d.wellKnown['matrix/server']) {
        matrixHostname.value = JSON.parse(d.wellKnown['matrix/server'])['m.server'];
      }
      if (d.wellKnown && d.wellKnown['host-meta']) {
        mastodonHostname.value = d.wellKnown['host-meta'].match(new RegExp('template="https://(.*?)/'))[1];
      }
      if (d.wellKnown && 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'];
        }
      }
    } catch (e) {
      console.error(e);
    }

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

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('domains.domainWellKnown.title', { domain })"
    :confirm-busy="busy"
    :confirm-label="$t('main.dialog.save')"
    :reject-label="busy ? null : $t('main.dialog.cancel')"
     reject-style="secondary"
    @confirm="onSubmit()"
  >
    <p v-html="$t('domains.domainDialog.wellKnownDescription', { domain, docsLink: 'https://docs.cloudron.io/domains/#well-known-locations' })"></p>

    <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.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>
