<script setup>

import { ref, onMounted, watch } from 'vue';
import { Switch } from 'pankow';
import Section from '../components/Section.vue';
import SettingsItem from '../components/SettingsItem.vue';
import ExternalLdap from '../components/ExternalLdap.vue';
import UserDirectoryModel from '../models/UserDirectoryModel.js';

const userDirectoryModel = UserDirectoryModel.create();

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

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

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

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')" :padding="false">
      <SettingsItem>
        <div>{{ $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>
        <Switch v-model="editableUserProfiles"/>
      </SettingsItem>

      <SettingsItem>
        <div>{{ $t('users.settings.require2FACheckbox') }}</div>
        <Switch v-model="mandatory2FA"/>
      </SettingsItem>
    </Section>

    <ExternalLdap />
  </div>
</template>
