<template>
  <v-container>
    <v-snackbar color="primary" v-model="snackbar" top>
      {{$t("Users.DeleteMessage")}}
      <v-btn color="pink" @click="deleteUser">{{$t("Users.YesBtn")}}</v-btn>
      <v-btn color="pink" @click="snackbar = false">{{$t("Users.NoBtn")}}</v-btn>
    </v-snackbar>
    <v-snackbar color="primary" v-model="alertSnackbar" :timeout="2000">{{alertText}}</v-snackbar>
    <v-dialog v-model="dialog" max-width="600px">
      <v-card>
        <v-card-title v-if="newOrEdit=='new' || newOrEdit=='edit' ">
          <span
            v-if="!$vuetify.rtl"
          >{{newOrEdit=="new"?$t("Users.newText"):$t("Users.editText")}} {{$t("Users.UserName")}}</span>
          <template v-if="$vuetify.rtl">
            <span v-if="newOrEdit=='new'">{{$t("Users.UserName")}} {{$t("Users.newText")}}</span>
            <span v-if="newOrEdit=='edit'">{{$t("Users.editText")}} {{$t("Users.UserName")}}</span>
          </template>
        </v-card-title>
        <v-card-title v-if=" newOrEdit=='reset'">
          <span>{{$t("Users.resetPassword")}}</span>
        </v-card-title>

        <v-card-text>
          <v-container>
            <div>
              <v-progress-linear :active="loading" :indeterminate="loading" color="cyan lighten-2"></v-progress-linear>
            </div>
            <v-row dense>
              <v-col cols="12" md="6" v-if="newOrEdit=='new'">
                <v-text-field
                  :label="$t('Users.UsernameTxtBox')"
                  v-model="UserForm.username"
                  prepend-icon="mdi-account-circle"
                  :hint="this.usernameAlert?`${$t('Register.usernameAlert')}`:''"
                  ref="usernameTextField"
                ></v-text-field>
              </v-col>
              <v-col cols="12" md="6" v-if="newOrEdit=='new' || newOrEdit == 'edit'">
                <v-text-field
                  :label="$t('Users.FullNameTxtBox')"
                  v-model="UserForm.fullName"
                  prepend-icon="mdi-rename-box"
                  ref="fullnameTextField"
                ></v-text-field>
              </v-col>
              <v-col cols="12" md="6" v-if="newOrEdit=='new' || newOrEdit == 'reset'">
                <!-- <v-text-field type="password" label="Password" v-model="UserForm.password" :rules="[rules.min]"></v-text-field> -->
                <v-text-field
                  :type="!showPassword1?'password' :'text'"
                  :label="$t('Register.password')"
                  prepend-icon="mdi-lock"
                  @click:append="showPassword1 = !showPassword1"
                  :append-icon="showPassword1 ? 'mdi-eye': 'mdi-eye-off'"
                  v-model="UserForm.password"
                  :rules="[rules.min]"
                  ref="firstPassTextField"
                  :hint="this.firstPassAlert?`${$t('Register.firstPassAlert')}`:''"
                />
              </v-col>
              <v-col cols="12" md="6" v-if="newOrEdit=='new' || newOrEdit == 'reset'">
                <v-text-field
                  :type="!showPassword2?'password' :'text'"
                  :label="$t('Register.repeatPassword')"
                  prepend-icon="mdi-lock"
                  @click:append="showPassword2 = !showPassword2"
                  :append-icon="showPassword2 ? 'mdi-eye': 'mdi-eye-off'"
                  v-model="secondPass"
                  :rules="[rules.matchPass]"
                  ref="secondPassTextField"
                  :hint="this.secondPassAlert?`${$t('Register.secondPassAlert')}`:''"
                />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="blue darken-1"
            text
            @click="createOrEditUser"
          >{{newOrEdit=="new"?$t("Users.createBtn"):$t("Users.editBtn")}}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-row justify="center" dense class="flex-wrap mb-6">
      <v-col md="7" lg="6" cols="12">
        <v-card tile>
          <v-card-actions>
            <v-row style="margin:auto">
              <v-col cols="12" class="d-flex justify-center align-center flex-wrap">
                <v-btn
                  color="rgb(94, 181, 177,.85)"
                  class="white--text ma-1"
                  @click="openNewDialog"
                >
                  <strong>{{$t("HISLink.newBtn")}}</strong>
                </v-btn>
                <v-btn
                  color="rgb(94, 181, 177,.85)"
                  class="white--text ma-1"
                  @click="openEditDialog"
                  :disabled="this.selectedItemInTable.length == 0"
                >
                  <strong>{{$t("HISLink.editBtn")}}</strong>
                </v-btn>
                <v-btn
                  color="rgb(94, 181, 177,.85)"
                  class="white--text ma-1"
                  @click="openResetDialog"
                  :disabled="this.selectedItemInTable.length == 0"
                >
                  <strong>{{$t("Users.ResetPasswordBtn")}}</strong>
                </v-btn>
                <v-btn
                  color="rgb(94, 181, 177,.85)"
                  class="white--text ma-1"
                  @click="deleteSnackbar"
                  :disabled="this.selectedItemInTable.length == 0"
                >
                  <strong>{{$t("HISLink.deleteBtn")}}</strong>
                </v-btn>
              </v-col>
            </v-row>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>
    <v-row justify="center" dense class="flex-wrap mt-6">
      <v-col md="9" cols="12">
        <v-card>
          <v-card-title>
            <v-spacer></v-spacer>
            <v-text-field
              v-model="search"
              append-icon="search"
              :label="$t('DataTableSearch')"
              single-line
              hide-details
              style="width:400px"
              class="flex-grow-0"
            ></v-text-field>
          </v-card-title>
          <v-data-table
            v-model="selectedItemInTable"
            :headers="headerOfTable"
            :items="itemsOfTable"
            item-key="_id"
            class="elevation-1"
            style="width:100%"
            fixed-header
            hide-default-footer
            disable-pagination
            show-select
            single-select
            :sort-by.sync="sortByTable"
            :sort-desc.sync="sortDescTable"
            height="62vh"
            @click:row="clickRow"
            :search="search"
          ></v-data-table>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>
<script>
import { log_init, logClient } from "../../imports/plugins/logger";
log_init();
export default {
  data() {
    return {
      sortByTable: undefined,
      sortDescTable: undefined,
      selectedItemInTable: [],
      dialog: false,
      newOrEdit: "",
      UserForm: {
        username: "",
        password: "",
        fullName: "",
        _id: ""
      },
      snackbar: false,
      alertSnackbar: false,
      alertText: "",
      loading: false,
      rules: {
        min: v => {
          if (v == undefined) return true;
          return v.length >= 5 || this.$t("Users.minimum5Character");
        },
        matchPass: v => {
          return (
            this.UserForm.password === this.secondPass ||
            this.$t("Register.matchPass")
          );
        }
      },
      usernameAlert: false,
      showPassword1: false,

      firstPassAlert: false,

      showPassword2: false,
      secondPass: null,
      secondPassAlert: false,
      search: ""
    };
  },
  computed: {
    headerOfTable() {
      let headers = ["username", "fullname"];
      let headerObjs = [];
      for (let header of headers) {
        headerObjs.push({
          text: header,
          value: header,
          class: "text-center",
          width: 180
        });
      }
      return headerObjs;
    },
    itemsOfTable() {
      this.loading = false;
      this.dialog = false;
      if (this.users && this.users.length > 0) {
        let users = [];
        for (let user of this.users) {
          users.push({
            username: user.username,
            fullname: user.profile.fullName,
            _id: user._id
          });
        }

        return users;
      }
      return [];
    }
  },
  methods: {
    clickRow(item) {
      if (
        this.selectedItemInTable.length > 0 &&
        this.selectedItemInTable[0]._id == item._id
      ) {
        this.selectedItemInTable = [];
      } else {
        this.selectedItemInTable = [];
        this.selectedItemInTable = [item];
      }
    },
    openNewDialog() {
      for (let prop in this.UserForm) {
        this.$set(this.UserForm, prop, "");
      }
      this.$set(this.UserForm, "_id", "");
      this.newOrEdit = "new";
      this.dialog = true;
    },
    openEditDialog() {
      if (this.selectedItemInTable.length == 0) {
        this.alertSnackbarMethod(this.$t("Users.userSelectStatement"));
        return;
      }
      for (let prop in this.UserForm) {
        if (this.selectedItemInTable[0][prop] != undefined) {
          this.$set(this.UserForm, prop, this.selectedItemInTable[0][prop]);
        }
      }
      this.$set(this.UserForm, "_id", this.selectedItemInTable[0]["_id"]);
      this.$set(
        this.UserForm,
        "fullName",
        this.selectedItemInTable[0]["fullname"]
      );
      this.newOrEdit = "edit";
      this.dialog = true;
    },
    openResetDialog() {
      this.UserForm.password = "";
      this.secondPass = "";
      if (this.selectedItemInTable.length == 0) {
        this.alertSnackbarMethod(this.$t("Users.userSelectStatement"));
        return;
      }

      this.$set(this.UserForm, "_id", this.selectedItemInTable[0]["_id"]);

      this.newOrEdit = "reset";
      this.dialog = true;
    },
    createOrEditUser() {
      this.loading = true;
      let me = this;

      if (this.newOrEdit == "new") {
        const username = this.UserForm.username;
        const password = this.UserForm.password;
        const that = this;

        if (username == null || username.length == 0) {
          this.$refs.usernameTextField.focus();
          this.usernameAlert = true;
          this.loading = false;
          return;
        }

        if (
          this.UserForm.password == null ||
          this.UserForm.password.length == 0
        ) {
          this.$refs.firstPassTextField.focus();
          this.firstPassAlert = true;
          this.loading = false;
          return;
        }

        if (this.secondPass == null || this.secondPass.length == 0) {
          this.$refs.secondPassTextField.focus();
          this.secondPassAlert = true;
          this.loading = false;
          return;
        }

        if (this.UserForm.password != this.secondPass) {
          this.alertSnackbarMethod(this.$t("Users.matchPassword"));
          this.loading = false;
          return;
        }

        if (this.UserForm.password.length < 5) {
          this.alertSnackbarMethod(this.$t("Users.minimum5Character"));
          this.loading = false;
          return;
        }

        if (this.UserForm.password == this.secondPass && username != null) {
          let item = {
            username: username,
            password: password,
            profile: {
              fullName: this.UserForm.fullName,
              language: { name: "English", alias: "en" },
              picture: "/img/empty.png"
            }
          };

          Meteor.call("createUser1", item, function(error, result) {
            if (error) {
              Meteor.settings.public.enableDebug
                ? logClient(
                    "error",
                    `createUser1 Method error`,
                    error,
                    Meteor.user().username
                  )
                : "";
            }
            me.loading = false;
            // me.dialog = false;
          });
        }
      }
      if (this.newOrEdit == "edit") {
        let item = {
          _id: this.UserForm._id,
          fullName: this.UserForm.fullName
        };
        Meteor.call("editUser1", item, function(error, result) {
          if (error) {
            Meteor.settings.public.enableDebug
              ? logClient(
                  "error",
                  `editUser1 Method error`,
                  error,
                  Meteor.user().username
                )
              : "";
          }
          me.selectedItemInTable = [];
          me.loading = false;
        });
      }

      if (this.newOrEdit == "reset") {
        if (
          this.UserForm.password == null ||
          this.UserForm.password.length == 0
        ) {
          this.$refs.firstPassTextField.focus();
          this.firstPassAlert = true;
          this.loading = false;
          return;
        }

        if (this.secondPass == null || this.secondPass.length == 0) {
          this.$refs.secondPassTextField.focus();
          this.secondPassAlert = true;
          this.loading = false;
          return;
        }

        if (this.UserForm.password != this.secondPass) {
          this.alertSnackbarMethod(this.$t("Users.matchPassword"));
          this.loading = false;
          return;
        }

        if (this.UserForm.password.length < 5) {
          this.alertSnackbarMethod(this.$t("Users.minimum5Character"));
          this.loading = false;
          return;
        }

        let item = {
          _id: this.UserForm._id,
          password: this.UserForm.password
        };
        Meteor.call("setPassword", item, function(error, result) {
          if (error) {
            Meteor.settings.public.enableDebug
              ? logClient(
                  "error",
                  `setPassword Method error`,
                  error,
                  Meteor.user().username
                )
              : "";
          }
          me.loading = false;
          me.dialog = false;
          // me.selectedItemInTable = [];
        });
      }
    },
    deleteUser() {
      let me = this;
      this.snackbar = false;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(this.$t("Users.userSelectStatement"));

        return;
      }
      let deleteUser = {};
      deleteUser._id = this.selectedItemInTable[0]["_id"];

      Meteor.call("deleteUser1", deleteUser, function(error, result) {
        if (error) {
          Meteor.settings.public.enableDebug
            ? logClient(
                "error",
                `deleteUser1 Method error`,
                error,
                Meteor.user().username
              )
            : "";
        }
        me.alertSnackbarMethod(this.$t("Users.userDeleteStatement"));
      });
    },
    deleteSnackbar() {
      this.snackbar = true;
    },
    alertSnackbarMethod(text) {
      this.alertText = text;
      this.alertSnackbar = true;
    }
    // beforeRouteEnter(to, from, next) {
    //   next(vm => {
    //     if (
    //       Meteor.userId() &&
    //       Meteor.users.findOne({ _id: Meteor.userId() }).username !=
    //         "marcoadmin"
    //     ) {
    //       vm.$router.push("/main/worklist");
    //     } else {
    //       vm.$router.push("/signin");
    //     }
    //   });
    // }
  },
  meteor: {
    $subscribe: {
      users: []
    },
    users() {
      return Meteor.users.find({ username: { $ne: "marcoadmin" } }).fetch();
    }
  }
};
</script>
<style>
</style>