<script setup>

import { ref, onMounted } from 'vue';
import { Button, Checkbox } from 'pankow';
import Section from '../components/Section.vue';
import ExternalLdap from '../components/ExternalLdap.vue';
import ExposedLdap from '../components/ExposedLdap.vue';
import OpenIdClients from '../components/OpenIdClients.vue';
import UserDirectoryModel from '../models/UserDirectoryModel.js';

const userDirectoryModel = UserDirectoryModel.create();

const editableUserProfiles = ref(false);
const mandatory2FA = ref(false);
const configBusy = ref(false);

async function onSubmitConfig() {
  configBusy.value = true;

  const [error] = await userDirectoryModel.setGlobalProfileConfig({ mandatory2FA: mandatory2FA.value, lockUserProfiles: !editableUserProfiles.value });
  if (error) console.error(error);

  configBusy.value = false;
}

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

  editableUserProfiles.value = !result.lockUserProfiles;
  mandatory2FA.value = result.mandatory2FA;
});

</script>

<template>
  <div class="content">
    <Section :title="$t('users.title')">
      <form role="form" novalidate @submit="onSubmitConfig()" autocomplete="off">
        <fieldset :disabled="configBusy">
          <div>
            <Checkbox v-model="editableUserProfiles" :label="$t('users.settings.allowProfileEditCheckbox')" /><sup><a href="https://docs.cloudron.io/user-directory/#lock-profile" target="_blank"><i class="fa fa-question-circle"></i></a></sup>
          </div>
          <div>
            <Checkbox v-model="mandatory2FA" :label="$t('users.settings.require2FACheckbox')" />
          </div>

          <br/>

          <Button @click="onSubmitConfig()" :disabled="configBusy" :loading="configBusy">{{ $t('users.settings.saveAction') }}</Button>
        </fieldset>
      </form>
    </Section>

    <ExternalLdap />
    <ExposedLdap />
    <OpenIdClients />
  </div>
</template>
