<template>
  <v-container>
    <v-snackbar color="primary" v-model="snackbar" top>
      {{$t("Client.DeleteMessage")}}
      <v-btn color="pink" @click="deleteClient">{{$t("Client.YesBtn")}}</v-btn>
      <v-btn color="pink" @click="snackbar = false">{{$t("Client.NoBtn")}}</v-btn>
    </v-snackbar>
    <v-snackbar :color="alertColor" v-model="alertSnackbar" :timeout="2000">{{alertText}}</v-snackbar>
    <v-dialog v-model="dialog" max-width="600px">
      <v-card>
        <v-card-title>
          <span>{{newOrEdit=="new"?$t("Client.newText"):$t("Client.editText")}} {{$t("Client.clientName")}}</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-text-field label="Caption" v-model="ClientForm.Caption"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="AETitle" type="text" v-model="ClientForm.AETitle"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Hostname" type="text" v-model="ClientForm.Hostname"></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field label="Port" type="text" v-model="ClientForm.Port"></v-text-field>
              </v-col>

              <v-col cols="12" md="6">
                <v-text-field
                  :label="$t('Client.AutoCompleteTimeSpanLabel')"
                  type="number"
                  v-model="ClientForm.AutoCompleteTimeSpan"
                  :rules="numberRules"
                  :disabled="!ClientForm.AutoComplete"
                  placeholder="1-23"
                ></v-text-field>
              </v-col>
              <v-col cols="12" md="6">
                <v-checkbox v-model="ClientForm.AutoComplete" class="mx-2" :label="$t('Client.AutoCompleteLabel')"></v-checkbox>
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="blue darken-1"
            text
            @click="createOrEditClient"
          >{{newOrEdit=="new"?$t("Client.createBtn"):$t("Client.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="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 Client from "../../imports/api/collections/clients.js";
import { Meteor } from "meteor/meteor";
// import { log_init, logClient } from "../../imports/plugins/logger";
// log_init();

export default {
  data() {
    return {
      sortByTable: undefined,
      sortDescTable: undefined,
      selectedItemInTable: [],
      dialog: false,
      newOrEdit: "",
      ClientForm: {
        Caption: "",
        AETitle: "",
        Hostname: "",
        Port: "",
        AutoComplete: false,
        AutoCompleteTimeSpan: 1,
        _id: ""
      },
      snackbar: false,
      alertSnackbar: false,
      alertText: "",
      alertColor: "primary",
      loading: false,
      search: "",
      maxLength: 24,
      minLength: 0,
      numberRules: [
        // v => !!v || "Input is required!",
        v =>
          v < this.maxLength ||
          this.$t("Client.lessThan25"),
        v =>
          v > this.minLength ||
          this.$t("Client.greaterThanZero")
      ]
    };
  },
  computed: {
    headerOfTable() {
      let headers = [
        "Caption",
        "AETitle",
        "Hostname",
        "Port",
        "AutoComplete",
        "AutoCompleteTimeSpan"
      ];
      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.clients && this.clients.length > 0) {
        return this.clients;
      }
      return [];
    }
  },
  methods: {
    clickRow(item) {
      if (
        this.selectedItemInTable.length > 0 &&
        this.selectedItemInTable[0]._id == item._id
      ) {
        this.selectedItemInTable = [];
      } else {
        this.selectedItemInTable = [];
        this.selectedItemInTable = [item];
      }
    },
    openNewDialog() {
      // logClient(
      //   "debug",
      //   `openNewDialog() => newDialog `,
      //   this.ClientForm,
      //   Meteor.user().username
      // );

      for (let prop in this.ClientForm) {
        this.$set(this.ClientForm, prop, "");
      }
      this.$set(this.ClientForm, "_id", "");
      this.$set(this.ClientForm, "AutoComplete", false);
      this.$set(this.ClientForm, "AutoCompleteTimeSpan", 1);
      this.newOrEdit = "new";
      this.dialog = true;
    },
    openEditDialog() {
      if (this.selectedItemInTable.length == 0) {
        this.alertSnackbarMethod(this.$t("Client.clientSelectStatement"));
        return;
      }
      for (let prop in this.ClientForm) {
        if (this.selectedItemInTable[0][prop] != undefined) {
          this.$set(this.ClientForm, prop, this.selectedItemInTable[0][prop]);
        }
      }
      this.$set(this.ClientForm, "_id", this.selectedItemInTable[0]["_id"]);
      this.newOrEdit = "edit";
      this.dialog = true;
    },
    createOrEditClient() {
      if (
        this.ClientForm.AutoComplete &&
        this.ClientForm.AutoCompleteTimeSpan <= 0
      ) {
        this.alertColor = "danger";
        this.alertText = this.$t("Client.greaterThanZero");
        this.alertSnackbar = true;
        return;
      }

      if (
        this.ClientForm.AutoComplete &&
        this.ClientForm.AutoCompleteTimeSpan > 24
      ) {
        this.alertColor = "danger";
        this.alertText = this.$t("Client.lessThan25");
        this.alertSnackbar = true;
        return;
      }

      this.loading = true;
      let me = this;
      if (this.newOrEdit == "new") {
        Meteor.call("createClient", this.ClientForm, function(error, result) {
          
        });
      }
      if (this.newOrEdit == "edit") {
        Meteor.call("editClient", this.ClientForm, function(error, result) {
          // me.dialog = false;
          me.selectedItemInTable = [];
        });
      }
    },
    deleteClient() {
      let me = this;
      this.snackbar = false;
      if (this.selectedItemInTable.length == 0) {
        me.alertSnackbarMethod(me.$t("Client.clientSelectStatement"));
        return;
      }
      let deleteHislink = {};
      deleteHislink._id = this.selectedItemInTable[0]["_id"];

      Meteor.call("deleteClient", deleteHislink, function(error, result) {
        if (error.reason == "relationShipError") {
          me.alertColor = "error";
          me.alertSnackbar = true;
          me.alertText = me.$t("Client.clientRelationshipError");
          return;
        }

        me.alertSnackbarMethod(me.$t("Client.clientDeleteStatement"));
      });
    },
    deleteSnackbar() {
      this.snackbar = true;
    },
    alertSnackbarMethod(text) {
      this.alertText = text;
      this.alertSnackbar = true;
    }
  },
  meteor: {
    $subscribe: {
      clients: []
    },
    clients() {
      return Client.find({}).fetch();
    }
  }
};
</script>
<style>
</style>