<script setup>

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, FormGroup, ClipboardButton, Checkbox, PasswordInput, TextInput, InputGroup } from '@cloudron/pankow';
import Section from './Section.vue';
import DomainsModel from '../models/DomainsModel.js';
import DashboardModel from '../models/DashboardModel.js';
import UserDirectoryModel from '../models/UserDirectoryModel.js';

const domainsModel = DomainsModel.create();
const dashboardModel = DashboardModel.create();
const userDirectoryModel = UserDirectoryModel.create();

const adminDomain = ref({});
const editError = ref({});
const busy = ref(false);
const enabled = ref(false);
const ldapUrl = ref('');
const secret = ref('');
const allowlist = ref('');

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

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

  busy.value = true;
  editError.value = {};

  const [error] = await userDirectoryModel.setExposedLdapConfig({ enabled: enabled.value, allowlist: allowlist.value, secret: secret.value });
  busy.value = false;

  if (error) {
    if (error.status === 400) {
      if (error.body.message.indexOf('secret') !== -1) editError.value.secret = error.body.message;
      else editError.value.allowlist = error.body.message;
    } else {
      editError.value.generic = error.body ? error.body.message : 'Internal error';
    }
  }
}

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

  const domains = result;

  [error, result] = await dashboardModel.config();
  if (error) return console.error(error);

  ldapUrl.value = `ldaps://${result.adminFqdn}:636`;
  adminDomain.value = domains.find(d => d.domain === result.adminDomain);

  [error, result] = await userDirectoryModel.getExposedLdapConfig();
  if (error) return console.error(error);

  enabled.value = result.enabled;
  secret.value = result.secret;
  allowlist.value = result.allowlist;

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

</script>

<template>
  <Section :title="$t('users.exposedLdap.title')">
    <div>{{ $t('users.exposedLdap.description') }}</div>

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

        <Checkbox v-model="enabled" :label="$t('users.exposedLdap.enabled')" help-url="https://docs.cloudron.io/user-directory/#ldap-directory-server"/>

        <FormGroup>
          <label for="ldapUrlInput">{{ $t('users.exposedLdap.secret.url') }}</label>
          <InputGroup>
            <TextInput id="ldapUrlInput" v-model="ldapUrl" readonly style="flex-grow: 1;"/>
            <ClipboardButton :value="ldapUrl" />
          </InputGroup>
          <div class="warning-label" v-show="adminDomain.provider === 'cloudflare'">{{ $t('users.exposedLdap.cloudflarePortWarning') }}</div>
        </FormGroup>

        <FormGroup>
          <label for="secretInput">{{ $t('users.exposedLdap.secret.label') }}</label>
          <div description v-html="$t('users.exposedLdap.secret.description', { userDN: 'cn=admin,ou=system,dc=cloudron' })"></div>
          <PasswordInput id="secretInput" v-model="secret" required :disabled="!enabled" />
          <div class="has-error" v-show="editError.secret">{{ editError.secret }}</div>
        </FormGroup>

        <FormGroup>
          <label for="allowlistInput">{{ $t('users.exposedLdap.ipRestriction.label') }}</label>
          <div description v-html="$t('users.exposedLdap.ipRestriction.description')"></div>
          <textarea id="allowlistInput" v-model="allowlist" rows="4" required :disabled="!enabled"></textarea>
          <small style="helper-text">{{ $t('users.exposedLdap.ipRestriction.placeholder') }}</small>
          <div class="has-error" v-show="editError.allowlist">{{ editError.allowlist }}</div>
        </FormGroup>
      </fieldset>
    </form>

    <div class="error-label" v-show="editError.generic">{{ editError.generic }}</div>

    <br/>
    <Button :loading="busy" :disabled="!isFormValid || busy" @click="onSubmit()">{{ $t('users.settings.saveAction') }}</Button>
  </Section>
</template>
