<template>
  <v-row v-if="formState.ready" v-resize="onResize">
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-col cols="12">
      <v-btn @click="refreshProfile">
        <v-icon>$ayiSync</v-icon>
      </v-btn>
    </v-col>
    <v-col cols="12">
      <v-card elevation="4" data-cy="profileCard">
        <v-card :height="cardHeight">
          <iframe
            id="profileFrame"
            style="width:100%;height:100%"
            :src="profileUrl()"
          ></iframe>
        </v-card>
      </v-card>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "ops-profile";
export default {
  data() {
    return {
      cardHeight: 300,
      formState: {
        ready: false,
        loading: false,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      window.$gz.eventBus.$on("menu-click", clickHandler);
      generateMenu(vm);
      this.formState.ready = true;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },

  methods: {
    onResize() {
      this.cardHeight = window.innerHeight * 0.85;
    },
    profileUrl() {
      return (
        window.$gz.api.ServerBaseUrl() +
        "profiler/results-index?t=" +
        this.$store.state.downloadToken
      );
    },

    refreshProfile() {
      const ifr = document.getElementById("profileFrame");
      //trigger refresh?  wtf?
      // eslint-disable-next-line no-self-assign
      ifr.src = ifr.src;
    }
  }
};

//////////////////////
//
//
function generateMenu() {
  const menuOptions = {
    isMain: true,
    icon: "$ayiBinoculars",
    title: "ServerProfiler",
    helpUrl: "ops-profile",
    formData: {
      ayaType: window.$gz.type.ServerMetrics
    },
    menuItems: []
  };

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

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations(["ServerProfiler"]);
}
</script>
