<template>
  <v-row v-if="formState.ready" dense>
    <v-col>
      <v-form ref="form">
        <v-row dense>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-radio-group
              v-model="obj.serverState"
              dense
              :mandatory="true"
              :readonly="formState.readOnly"
              @change="fieldValueChanged('serverState')"
            >
              <v-radio
                :label="$ay.t('ServerStateOpen')"
                value="Open"
                data-cy="serverStateOpen"
              ></v-radio>
              <v-radio
                :label="$ay.t('ServerStateMigrateMode')"
                value="MigrateMode"
              ></v-radio>
              <v-radio
                :label="$ay.t('ServerStateOps')"
                value="OpsOnly"
              ></v-radio>
            </v-radio-group>
          </v-col>
          <v-col cols="12">
            <v-textarea
              ref="reason"
              v-model="obj.reason"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('ServerStateReason')"
              :error-messages="form().serverErrors(this, 'reason')"
              data-cy="reason"
              auto-grow
              @input="fieldValueChanged('reason')"
            ></v-textarea>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "ops-server-state";
const API_BASE_URL = "server-state/";
const FORM_CUSTOM_TEMPLATE_KEY = "ServerState";
export default {
  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()
    };
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const 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
    }
  },
  async created() {
    const 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);
  },
  methods: {
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get(API_BASE_URL);
        vm.formState.ready = true;
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          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 submit() {
      const vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        try {
          const res = await window.$gz.api.upsert(API_BASE_URL, vm.obj);
          vm.formState.loading = false;
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            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() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.upsert("server-state/shutdown", {});
        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;
  }
  const 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) {
  const menuOptions = {
    isMain: true,
    readOnly: vm.formState.readOnly,
    icon: "$ayiDoorOpen",
    title: "ServerState",
    helpUrl: "ops-server-state",
    formData: {
      ayaType: window.$gz.type.ServerState
    },
    menuItems: []
  };

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

    if (!window.$gz.store.state.globalSettings.sBuild)
      //not available to service build (subscription build)
      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() {
  await fetchTranslatedText();
}

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