<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-radio-group
              v-model="obj.serverState"
              :mandatory="true"
              :readonly="formState.readOnly"
              :disabled="formState.readOnly"
              @change="fieldValueChanged('serverState')"
            >
              <v-radio
                :label="$ay.t('ServerStateOpen')"
                value="Open"
                data-cy="serverStateOpen"
              ></v-radio>
              <v-radio
                :label="$ay.t('ServerStateOps')"
                value="OpsOnly"
              ></v-radio>
            </v-radio-group>
          </v-col>
          <v-col cols="12">
            <v-textarea
              v-model="obj.reason"
              :readonly="formState.readOnly"
              :disabled="formState.readOnly"
              :label="$ay.t('ServerStateReason')"
              :error-messages="form().serverErrors(this, 'reason')"
              ref="reason"
              data-cy="reason"
              @input="fieldValueChanged('reason')"
              auto-grow
              :clearable="!formState.readOnly"
            ></v-textarea>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "ops-server-state";
const API_BASE_URL = "server-state/";
const FORM_CUSTOM_TEMPLATE_KEY = "ServerState"; //<-- Should always be CoreBizObject AyaType name here where possible

export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.getRights(window.$gz.type.ServerState);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      await vm.getDataFromApi();
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj: {
        serverState: "",
        reason: ""
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject()
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        let canSave = val.dirty && val.valid && !val.readOnly;
        if (canSave) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    }
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  methods: {
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;
      let url = API_BASE_URL;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        vm.formState.ready = true;
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;

          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          //modify the menu as necessary
          generateMenu(vm);
        }
      } catch (error) {
        //Update the form status
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async submit() {
      let vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;
        let url = API_BASE_URL;

        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        try {
          let res = await window.$gz.api.upsert(url, vm.obj);

          vm.formState.loading = false;
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //UserOptions is never a POST as it always exists and can't be deleted so always a PUT

            //Handle "put" of an existing record (UPDATE)
            vm.obj.concurrency = res.data.concurrency;
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false
            });
          }
        } catch (error) {
          vm.formState.loading = false;
          window.$gz.errorHandler.handleFormError(error, vm);
        }
      }
    },
    async shutdown() {
      let vm = this;
      vm.formState.loading = true;
      let url = "server-state/shutdown";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.upsert(url, {});
        vm.formState.loading = false;
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.$router.push("/login");
        }
      } catch (error) {
        vm.formState.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 "save":
        m.vm.submit();
        break;
      case "shutdown":
        if (
          (await window.$gz.dialog.confirmGeneric(
            "AreYouSureShutDown",
            "warning"
          )) === true
        ) {
          m.vm.shutdown();
        }
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiDoorOpen",
    title: "ServerState",
    helpUrl: "form-ops-server-state",
    formData: {
      ayaType: window.$gz.type.ServerState
    },
    formData: {
      // ayaType: window.$gz.type.UserOptions
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });

    menuOptions.menuItems.push({
      title: "ShutDownServer",
      icon: "$ayiStopCircle",
      surface: false,
      key: FORM_KEY + ":shutdown",
      vm: vm
    });
  }

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

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "ServerStateOpen",
    "ServerStateOps",
    "ServerStateReason",
    "ShutDownServer",
    "AreYouSureShutDown"
  ]);
}
</script>
