<script setup>

import { ref, onMounted } from 'vue';
import { Button } from 'pankow';
import AccessControl from '../AccessControl.vue';
import AppsModel from '../../models/AppsModel.js';
import { ACL_OPTIONS } from '../../constants.js';

const props = defineProps([ 'app' ]);

const appsModel = AppsModel.create();

const busy = ref(false);
const errorMessage = ref('');
const accessRestrictionOption = ref(ACL_OPTIONS.ANY);
const accessRestrictionAcl = ref({ users: [], groups: [] });

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

  const data = {
    accessRestriction: accessRestrictionOption.value === ACL_OPTIONS.ANY ? null : (accessRestrictionOption.value === ACL_OPTIONS.NOSSO ? false : accessRestrictionAcl.value)
  };

  const [error] = await appsModel.configure(props.app.id, 'access_restriction', data);
  if (error) {
    errorMessage.value = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  busy.value = false;
}

onMounted(() => {
  if (props.app.accessRestriction === null) {
    accessRestrictionOption.value = ACL_OPTIONS.ANY;
    accessRestrictionAcl.value = { users: [], groups: [] };
  } else if (props.app.accessRestriction === false) {
    accessRestrictionOption.value = ACL_OPTIONS.NOSSO;
    accessRestrictionAcl.value = { users: [], groups: [] };
  } else {
    accessRestrictionOption.value = ACL_OPTIONS.RESTRICTED;
    accessRestrictionAcl.value = props.app.accessRestriction;
  }
});

</script>

<template>
  <div>
    <div class="text-danger" v-if="errorMessage">{{ errorMessage }}</div>
    <AccessControl v-model:option="accessRestrictionOption" v-model:acl="accessRestrictionAcl" :manifest="app.manifest" :hide-optional-sso-option="!app.sso"/>
    <br/>
    <Button @click="onSubmit()" :loading="busy" :disabled="busy">{{ $t('main.dialog.save') }}</Button>
  </div>
</template>
