<template>

  <div>

    <box variant="border">

      <div class="active-user"> Currently selected user: {{ activeUser }}</div>
    </box>


    <modal-dialog title="Do you want to change active user?" :state="showModal"
                  :message="`Do you want to set the active user to: ${userName}`" accept-text="Yes" dismiss-text="No"
                  @click="activateUser"></modal-dialog>
    <table-view :columns="columns" :data-source="fetch" @row-click="selectUser" :mouse-over="true"></table-view>

  </div>


</template>

<script>

import performRequest from "@/backend.js";
import {config} from "@/config.js";
import TableView from "@/components/UI/TableView.vue";
import ModalDialog from "@/components/UI/ModalDialog.vue";
import Box from "@/components/UI/Box.vue";

export default {
  name: "DevUserControl",
  components: {Box, ModalDialog, TableView},
  created() {
    this.getActiveUser();
  },
  methods: {
    async fetch() {
      const resp = await performRequest(null, "GET", `${config.backendUrl}/dev/user`, null);
      this.users = resp.data;
      return this.users;
    },
    selectUser(user) {
      this.selectedUser = user;
      this.showModal = true;

    },
    async activateUser(action) {
      if (action === "accept") {
        await performRequest(null, "POST", `${config.backendUrl}/dev/user`, this.selectedUser, false);
        await this.getActiveUser();
      }
      this.showModal = false;
    },
    async getActiveUser() {
      const resp = await performRequest(null, "GET", `${config.backendUrl}/active-user`, null);
      this.activeUserData = resp.data;
    }
  },
  computed: {
    userName() {
      return this.selectedUser?.firstname + " " + this.selectedUser?.lastname;
    },
    activeUser() {
      return this.activeUserData?.firstname + " " + this.activeUserData?.lastname;
    }
  },
  data() {
    return {
      showModal: false,
      activeUserData: null,
      selectedUser: null,
      users: null,
      columns: [
        {
          key: 'firstname',
          label: 'First name',
        },
        {
          key: 'lastname',
          label: 'Last name',
        },
        {
          key: 'mail',
          label: 'E-Mail',
        },
        {
          key: 'workday_id',
          label: 'Workday ID',
        },
        {
          key: 'groups',
          label: 'User groups',
          formatter: (value) => {
            return value.join(", ")
          }
        },
        {
          key: 'is_active',
          label: 'active',
          formatter: (value) => {
            return value ? 'Yes' : 'No';
          }
        },
      ],
      pagination: {
        page: 1,
        pageCount: 1,
        totalCount: 0
      },
      pageSize: 20
    }
  },

}
</script>


<style scoped>

.active-user {
  font-size: 1.6rem
}

</style>