<template>
  <div>
    <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
    <v-data-table
      v-model="selected"
      :headers="headers"
      :items="obj"
      class="elevation-1"
      :disable-pagination="true"
      :disable-filtering="true"
      hide-default-footer
      @click:row="rowClick"
      :sort-by="['name']"
      show-select
      :header-props="{ sortByText: $ay.t('Sort') }"
    >
      <template v-slot:[`item.active`]="{ item }">
        <v-simple-checkbox v-model="item.active" disabled></v-simple-checkbox>
      </template>
    </v-data-table>
  </div>
</template>

<script>
const FORM_KEY = "adm-users";
export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.getRights(window.$gz.type.User);
      vm.formState.readOnly = !vm.rights.change;
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      await vm.getDataFromApi();
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },

  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      obj: [],
      headers: [],
      selected: [],
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      availableRoles: [],
      timeZoneName: window.$gz.locale.getBrowserTimeZoneName(),
      languageName: window.$gz.locale.getBrowserLanguages(),
      hour12: window.$gz.locale.getHour12()
    };
  },
  methods: {
    rowClick(item) {
      window.$gz.eventBus.$emit("openobject", {
        type: window.$gz.type.User,
        id: item.id,
        inside: false
      });
    },
    rolesDisplayFromRoles(roles) {
      let roleNames = [];
      if (roles != null && roles != 0) {
        for (let i = 0; i < this.availableRoles.length; i++) {
          let role = this.availableRoles[i];
          if (!!(roles & role.id)) {
            roleNames.push(role.name);
          }
        }
      }
      return roleNames.join(", ");
    },
    async getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;

      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get("user/outlist");

        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.eventBus.$emit("notify-error", vm.$ay.t("ErrorAPI2010"));
            window.$gz._.delay(function() {
              vm.$router.go(-1);
            }, 2000);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data) {
            /*   Id = z.Id,
                Active = z.Active,
                Name = z.Name,
                UserType = z.UserType,
                LastLogin = z.LastLogin */
            let ret = [];
            for (let i = 0; i < res.data.length; i++) {
              let o = res.data[i];
              ret.push({
                id: o.id,
                name: o.name,
                active: o.active,
                userType: window.$gz.enums.get("outsideusertype", o.userType),
                lastLogin: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
                  o.lastLogin,
                  this.timeZoneName,
                  this.languageName,
                  this.hour12
                ),
                roles: this.rolesDisplayFromRoles(o.roles)
              });
            }

            vm.obj = ret;
          } else {
            vm.rawObj = [];
            vm.obj = [];
          }

          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          generateMenu(vm);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "new":
        m.vm.$router.push({
          name: "cust-user",
          params: { recordid: 0 }
        });
        break;
      // case "extensions":
      //   let res = await m.vm.$refs.extensions.open();
      //   break;
      case "directnotify":
        //nav to direct notify with list of users appended to route
        if (m.vm.selected.length == 0) {
          m.vm.$router.push({
            name: "home-notify-direct"
          });
        } else {
          m.vm.$router.push({
            name: "home-notify-direct",
            params: { userIdList: m.vm.selected.map(z => z.id).toString() }
          });
        }
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-users",
    title: "UserList",
    helpUrl: "form-cust-users",
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "New",
      icon: "fa-plus",
      surface: true,
      key: FORM_KEY + ":new",
      vm: vm
    });
  }

  //STUB REPORTS
  //Report not Print, print is a further option
  menuOptions.menuItems.push({
    title: "Report",
    icon: "fa-file-alt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  menuOptions.menuItems.push({
    title: "stub: Last report used",
    icon: "fa-file-alt",
    key: FORM_KEY + ":report:STUBlastusedreportid",
    vm: vm
  });

  // menuOptions.menuItems.push({
  //   title: "Extensions",
  //   icon: "fa-puzzle-piece",
  //   key: FORM_KEY + ":extensions",
  //   vm: vm
  // });

  menuOptions.menuItems.push({
    title: "DirectNotification",
    icon: "fa-comment-alt",
    key: FORM_KEY + ":directnotify",
    vm: vm
  });

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  await cacheEnums(vm);
  await createTableHeaders(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "User",
    "Active",
    "UserType",
    "LastLogin"
  ]);
}

//////////////////////
//
//
async function cacheEnums(vm) {
  //ensure the enum values required are pre-fetched
  await window.$gz.enums.fetchEnumList("outsideusertype");
  await window.$gz.enums.fetchEnumList("AuthorizationRoles");
  vm.availableRoles = window.$gz.enums.getSelectionList("AuthorizationRoles");
}

//////////////////////
//
//
async function createTableHeaders(vm) {
  vm.headers = [
    { text: vm.$ay.t("User"), value: "name" },
    { text: vm.$ay.t("Active"), value: "active" },
    { text: vm.$ay.t("UserType"), value: "userType" },
    { text: vm.$ay.t("LastLogin"), value: "lastLogin" }
  ];
}
</script>
