<script setup>
import { list, m, useLight, navigateTo } from "#imports";
import { ref, computed } from "vue";
const light = useLight();
if (!light.isGranted("system.view_as")) {
  await navigateTo("/");
}
let users = await list("User", {
  user_id: true,
  username: true,
  name: true,
  roles: true,
  email: true
}).fetch();
let columns = [
  {
    label: "Username",
    name: "username",
    field: "username",
    align: "left",
    sortable: true
  },
  {
    name: "name",
    label: "Name",
    field: "name",
    align: "left",
    sortable: true
  },
  {
    name: "email",
    label: "Email",
    align: "left",
    field: "email",
    sortable: true
  },
  {
    name: "roles",
    label: "Roles",
    align: "left",
    field: (r) => r.roles.join(",")
  },
  {
    name: "view",
    label: "View",
    align: "left"
  }
];
const onCickView = async (id) => {
  try {
    if (await m("viewAs", { user_id: id })) {
      window.location.href = "/";
    }
  } catch (e) {
    light.dialog({
      title: "Error",
      message: e.message,
      color: "negative",
      ok: true
    });
  }
};
const filter = ref("");
const filtered = computed(() => {
  if (!filter.value) return users;
  return users.filter((row) => {
    return Object.values(row).some((val) => {
      return String(val).toLowerCase().includes(filter.value.toLowerCase());
    });
  });
});
</script>

<template>
    <l-page class="q-gutter-md">
        <q-banner>
            Use this page to view the system as another user. This is useful for testing permissions.
        </q-banner>

        <q-table flat :columns="columns" :rows="filtered" :rows-per-page-options="[0]" dense bordered="">
            <template v-slot:top-right>
                <q-input outlined dense debounce="300" v-model="filter" placeholder="Search" clearable>
                    <template v-slot:append>
                        <q-icon name="sym_o_search" />
                    </template>
                </q-input>
            </template>

            <template #body-cell-view="props">
                <q-td :props="props">
                    <q-btn round circle flat dense @click="onCickView(props.row.user_id)" icon="sym_o_search"></q-btn>
                </q-td>
            </template>
        </q-table>
    </l-page>
</template>
