<template>
  <div>
    <FormGroup>
    <label>{{ $t('app.accessControl.userManagement.dashboardVisibility') }} <sup><a href="https://docs.cloudron.io/apps/#dashboard-visibility" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
      <Radiobutton v-model="accessRestrictionOption" :value="OPTIONS.ANY" :label="$t('app.accessControl.userManagement.visibleForAllUsers')"/>
      <Radiobutton v-model="accessRestrictionOption" :value="OPTIONS.RESTRICT" :label="$t('app.accessControl.userManagement.visibleForSelected')"/>
    </FormGroup>

    <div v-if="accessRestrictionOption === OPTIONS.RESTRICT">
      <div style="margin-left: 20px; display: flex;">
        <div>
          {{ $t('appstore.installDialog.users') }}: <MultiSelect v-model="accessRestriction.users" :options="users" option-label="username" />
        </div>
        <div>
          {{ $t('appstore.installDialog.groups') }}: <MultiSelect v-model="accessRestriction.groups" :options="groups" option-label="name" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>

import { ref, onMounted, defineModel, watch } from 'vue';
import { FormGroup, Radiobutton, MultiSelect } from 'pankow';
import UsersModel from '../models/UsersModel.js';
import GroupsModel from '../models/GroupsModel.js';

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;

const OPTIONS = Object.freeze({
  ANY: 'any',
  RESTRICTED: 'restricted',
});

const usersModel = UsersModel.create(API_ORIGIN, localStorage.token);
const groupsModel = GroupsModel.create(API_ORIGIN, localStorage.token);

const accessRestrictionOption = ref(OPTIONS.ANY);
const accessRestriction = ref({ users: [], groups: [] });
const users = ref([]);
const groups = ref([]);
const model = defineModel({ type: Object });

watch(accessRestrictionOption, (value) => {
  if (value === OPTIONS.ANY) model.value = null;
  else model.value = accessRestriction.value;
});

onMounted(async () => {
  users.value = await usersModel.list();
  groups.value = await groupsModel.list();
});

</script>

<style scoped>
</style>
