<template>
  <q-card>
    <q-card bordered v-for="(permission, index) in localPermission" v-bind:key="index">
      <q-card-section class="text-center">
        <div class="text-h7 text-bold text-primary">{{ $t(permission.name) }}</div>
      </q-card-section>
      <q-separator></q-separator>
      <div class="flex justify-center">
        <q-checkbox
          class="q-mx-md"
          :model-value="isFlagSet(permission.permission, 1 << 0)"
          @update:model-value="(val) => toggleBit(index, 0, val)"
          >{{ i18n.global.t('read') }}</q-checkbox
        >
        <q-checkbox
          class="q-mx-md"
          :model-value="isFlagSet(permission.permission, 1 << 1)"
          @update:model-value="(val) => toggleBit(index, 1, val)"
          >{{ i18n.global.t('write') }}</q-checkbox
        >
        <q-checkbox
          class="q-mx-md"
          :model-value="isFlagSet(permission.permission, 1 << 2)"
          @update:model-value="(val) => toggleBit(index, 2, val)"
          >{{ i18n.global.t('delete') }}</q-checkbox
        >
        <q-checkbox
          v-if="permission.permissionNumber > 3"
          class="q-mx-md"
          :model-value="isFlagSet(permission.permission, 1 << 3)"
          @update:model-value="(val) => toggleBit(index, 3, val)"
          >{{ i18n.global.t('import') }}</q-checkbox
        >
        <q-checkbox
          v-if="permission.permissionNumber > 4"
          class="q-mx-md"
          :model-value="isFlagSet(permission.permission, 1 << 4)"
          @update:model-value="(val) => toggleBit(index, 4, val)"
          >{{ i18n.global.t('export') }}</q-checkbox
        >
      </div>
    </q-card>
  </q-card>
</template>

<script setup lang="ts">
import { ref, type PropType } from 'vue';
import type { Permissions } from './permissions';
import { i18n } from 'src/boot/lang';

const props = defineProps({
  permissions: {
    type: Object as PropType<Permissions>,
    required: true,
  },
});

const emit = defineEmits(['update']);

const localPermission = ref(
  props.permissions.map((e) => ({
    name: e.name,
    permission: e.permission ?? 0,
    permissionNumber: e.name === 'members' ? 5 : 3,
  })),
);

function isFlagSet(mask: number, flag: number) {
  return (mask & flag) !== 0;
}

function toggleBit(index: number, bit: number, value: boolean) {
  const item = localPermission.value[index];
  if (!item) return; // guard against undefined index

  const mask = 1 << bit;
  const current = item.permission ?? 0;

  item.permission = value ? current | mask : current & ~mask;
  emit('update', localPermission.value);
}
</script>
