<template>
  <v-layout v-if="this.formState.ready">
    <v-flex>
      <v-form ref="form">
        <v-layout align-center justify-left row wrap>
          <v-flex xs12 mt-1 mb-2>
            <v-alert
              ref="errorbox"
              v-show="formState.errorBoxMessage"
              color="error"
              icon="fa-exclamation-circle "
              value="true"
              transition="scale-transition"
              class="multi-line"
              outline
            >{{ formState.errorBoxMessage }}</v-alert>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.name"
              :readonly="this.formState.readOnly"
              clearable
              @click:clear="onChange('name')"
              :counter="255"
              :label="this.$gzlocale.get('WidgetName')"
              :rules="[
                this.$gzform.max255(this, 'name'),
                this.$gzform.required(this, 'name')
              ]"
              :error-messages="this.$gzform.serverErrors(this, 'name')"
              ref="name"
              @change="onChange('name')"
            ></v-text-field>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.serial"
              :readonly="this.formState.readOnly"
              clearable
              @click:clear="onChange('serial')"
              :counter="10"
              :label="this.$gzlocale.get('WidgetSerial')"
              :rules="[this.$gzform.maxLength(this, 'serial', 10)]"
              :error-messages="this.$gzform.serverErrors(this, 'serial')"
              ref="serial"
              @change="onChange('serial')"
            ></v-text-field>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.count"
              :readonly="this.formState.readOnly"
              clearable
              @click:clear="onChange('count')"
              :counter="10"
              :label="this.$gzlocale.get('WidgetCount')"
              ref="count"
              :rules="[
                this.$gzform.integerValid(this, 'count'),
                this.$gzform.required(this, 'count')
              ]"
              :error-messages="this.$gzform.serverErrors(this, 'count')"
              required
              @change="onChange('count')"
              type="number"
            ></v-text-field>
          </v-flex>

          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.dollarAmount"
              :readonly="this.formState.readOnly"
              :prefix="this.$gzlocale.formats.currencySymbol"
              :label="this.$gzlocale.get('WidgetDollarAmount')"
              ref="dollarAmount"
              required
              :rules="[
                this.$gzform.decimalValid(this, 'dollarAmount'),
                this.$gzform.required(this, 'dollarAmount')
              ]"
              :error-messages="this.$gzform.serverErrors(this, 'dollarAmount')"
              @change="onChange('dollarAmount')"
              type="number"
            ></v-text-field>
          </v-flex>

          <v-flex xs12 sm6 lg4 xl3 px-2>
            <gz-date-time-picker
              :label="this.$gzlocale.get('WidgetStartDate')"
              v-model="obj.startDate"
              :readonly="this.formState.readOnly"
              ref="startDate"
              :error-messages="this.$gzform.serverErrors(this, 'startDate')"
              @change="onChange('startDate')"
            ></gz-date-time-picker>
          </v-flex>

          <v-flex xs12 sm6 lg4 xl3 px-2>
            <gz-date-time-picker
              :label="this.$gzlocale.get('WidgetEndDate')"
              :rules="[
                this.$gzform.datePrecedence(this, 'startDate', 'endDate')
              ]"
              :error-messages="this.$gzform.serverErrors(this, 'endDate')"
              v-model="obj.endDate"
              :readonly="this.formState.readOnly"
              ref="endDate"
              @change="onChange('endDate')"
            ></gz-date-time-picker>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-checkbox
              v-model="obj.active"
              :readonly="this.formState.readOnly"
              :label="this.$gzlocale.get('Active')"
              ref="active"
              :error-messages="this.$gzform.serverErrors(this, 'active')"
              required
              @change="onChange('active')"
            ></v-checkbox>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.roles"
              :readonly="this.formState.readOnly"
              :label="this.$gzlocale.get('WidgetRoles')"
              ref="roles"
              :rules="[
                this.$gzform.integerValid(this, 'roles'),
                this.$gzform.required(this, 'roles')
              ]"
              :error-messages="this.$gzform.serverErrors(this, 'roles')"
              required
              @change="onChange('roles')"
              type="number"
            ></v-text-field>
          </v-flex>
        </v-layout>

        <v-layout align-left justify-center row wrap mt-5>
          <v-flex xs6 sm4>
            READY: {{ formState.ready }}
            <br>
            LOADING: {{ formState.loading }}
            <br>
            DIRTY: {{ formState.dirty }}
            <br>
            VALID: {{ formState.valid }}
            <br>
            READONLY: {{ formState.readOnly }}
            <br>
          </v-flex>
        </v-layout>
      </v-form>
    </v-flex>
  </v-layout>
</template>

<script>
/*  eslint-disable    */

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  var m = this.$gzmenu.parseMenuItem(menuItem);
  if (m.owner == "inventory-widget-edit" && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      default:
        alert("inventory-widget-edit.vue::context click: [" + m.key + "]");
    }
  }
}

//////////////////////
//
//
function generateMenu(vm, readOnly) {
  var menuOptions = {
    isMain: false,
    icon: "fa-splotch",
    title: vm.$gzlocale.get("Widget"),
    helpUrl: "intro/#searching",
    menuItems: []
  };

  if (readOnly != true) {
    menuOptions.menuItems = [
      {
        title: vm.$gzlocale.get("Save"),
        icon: "save",
        surface: true,
        key: "inventory-widget-edit:save",
        vm: vm
      },
      {
        title: vm.$gzlocale.get("Delete"),
        icon: "trash-alt",
        surface: true,
        key: "inventory-widget-edit:delete",
        vm: vm
      },
      { divider: true, inset: false },
      {
        title: vm.$gzlocale.get("Duplicate"),
        icon: "clone",
        key: "inventory-widget-edit:duplicate",
        vm: vm
      }
    ];
  }

  vm.$gzevent.$emit("menu-change", menuOptions);
}

export default {
  beforeCreate() {
    //Cache all required lt keys
    var ltKeysRequired = [
      "Widget",
      "WidgetName",
      "WidgetSerial",
      "WidgetDollarAmount",
      "WidgetCount",
      "WidgetRoles",
      "WidgetStartDate",
      "WidgetEndDate",
      "WidgetNotes",
      "WidgetCustom1",
      "WidgetCustom2",
      "WidgetCustom3",
      "WidgetCustom4",
      "WidgetCustom5",
      "WidgetCustom6",
      "WidgetCustom7",
      "WidgetCustom8",
      "WidgetCustom9",
      "WidgetCustom10",
      "WidgetCustom11",
      "WidgetCustom12",
      "WidgetCustom13",
      "WidgetCustom14",
      "WidgetCustom15",
      "WidgetCustom16"
    ];
    var vm = this;
    this.$gzlocale
      .fetch(ltKeysRequired)
      // .then(function() {
      //   generateMenu(vm, );
      // })
      .then(() => (vm.formState.ready = true))
      .catch(err => {
        vm.formState.ready = true;
        vm.$gzHandleFormError(err);
      });
  },
  created() {
    this.$gzevent.$on("menu-click", clickHandler);
    this.getDataFromApi();
  },
  beforeDestroy() {
    this.$gzevent.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      obj: {},
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        var canSave = val.dirty && val.valid && !val.readOnly;
        if (canSave) {
          this.$gzevent.$emit("menu-enable-item", "inventory-widget-edit:save");
        } else {
          this.$gzevent.$emit(
            "menu-disable-item",
            "inventory-widget-edit:save"
          );
        }
      },
      deep: true
    }
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  methods: {
    onChange(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        this.$gzform.onChange(this, ref);
      }
    },
    getDataFromApi() {
      this.formState.loading = true;
      var url = "Widget/" + this.$route.params.id;
      var vm = this;
      this.$gzform.deleteAllErrorBoxErrors(this);
      this.$gzapi
        .get(url)
        .then(res => {
          if (res.error) {
            vm.formState.serverError = res.error;
            vm.$gzform.setErrorBoxErrors(vm);
          } else {
            vm.obj = res.data;
            //Update the form status
            vm.$gzform.setFormState({
              vm: vm,
              dirty: false,
              valid: true,
              loading: false,
              readOnly: res.readOnly ? true : false
            });

            //modify the menu as necessary
            generateMenu(vm, res.readOnly);
          }
        })
        .catch(function handleGetDataFromAPIError(error) {
          //Update the form status
          vm.$gzform.setFormState({
            vm: vm,
            loading: false
          });
          vm.$gzHandleFormError(error, vm);
        });
    },
    submit() {
      if (this.canSave) {
        this.formState.loading = true;
        var vm = this;
        var url = "Widget/" + this.$route.params.id;

        //clear any errors vm might be around from previous submit
        this.$gzform.deleteAllErrorBoxErrors(this);

        this.$gzapi
          .upsert(url, this.obj)
          .then(res => {
            this.formState.loading = false;
            if (res.error) {
              vm.formState.serverError = res.error;
              vm.$gzform.setErrorBoxErrors(vm);
            } else {
              //Logic for detecting if a post or put: if id then it was a post, if no id then it was a put
              if (res.id) {
                //Handle "post" of new record
                vm.obj = res.data;
                vm.$gzform.setFormState({
                  vm: vm,
                  dirty: false,
                  readOnly: res.readOnly ? true : false
                });
              } else {
                //Handle "put" of an existing record
                vm.obj.concurrencyToken = res.data.concurrencyToken;
                vm.$gzform.setFormState({
                  vm: vm,
                  dirty: false
                });
              }
            }
          })
          .catch(function handleSubmitError(error) {
            vm.formState.loading = false;
            vm.$gzHandleFormError(error, vm);
          });
      }
    },
    remove() {
      //Prompt:

      //do the delete
      this.formState.loading = true;
      var url = "Widget/" + this.$route.params.id;
      //TODO: check if it's a new record (no ID) or one from server (has id)
      var vm = this;
      this.$gzform.deleteAllErrorBoxErrors(this);
      this.$gzapi
        .remove(url)
        .then(res => {
          if (res.error) {
            vm.formState.serverError = res.error;
            vm.$gzform.setErrorBoxErrors(vm);
          } else {
            //success, navigate backwards
            vm.$router.go(-1);
          }
        })
        .catch(function handleGetDataFromAPIError(error) {
          //Update the form status
          vm.$gzform.setFormState({
            vm: vm,
            loading: false
          });
          vm.$gzHandleFormError(error, vm);
        });
    },
    duplicate() {
      console.log("About to dialog");
      

    this.$dialog.confirm({
      text: "Do you really want to exit?",
      title: "Warning"
    }).then(res => {
      console.log("The dialog result is:");
      console.log(res);
    });


      //console.log(this.$gzform.confirm(this));



      // this.$dialog.error({
      //   text: "Cannot delete this item",
      //   title: "Error"
      // });
      console.log("Done dialog");

      // this.$dialog.notify.info("Test notification", {
      //   position: "top-right",
      //   timeout: 5000
      // });

      // this.$dialog.message.info("Test", {
      //   position: "top-left"
      // });
      // this.$gzevent.$emit(
      //   "popup-message",
      //   "This is a test popup message\r\nDUPLICATE ALL THE THINGS!"
      // );
      //only if not dirty
      //check rights
      //duplicate
      //navigate to new record
      //alert("STUB: DUPLICATE");
    },
    stubTestClick() {
      this.$gzevent.$emit("menu-replace-item", {
        title: this.$gzlocale.get("Save"),
        surface: true,
        icon: "save",
        color: "error",
        disabled: true,
        key: "inventory-widget-edit:save"
      });
      // alert("stub test click");
    }
  }
};
</script>

<style></style>
