<template>
  <v-row v-if="formState.ready">
    <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
    <v-col cols="12" v-if="showSelector">
      <v-dialog
        scrollable
        max-width="600px"
        v-model="showSelector"
        @keydown.esc="cancel"
        data-cy="dashSelector"
      >
        <v-card elevation="24">
          <v-card-title class="headline lighten-2" primary-title>
            <span> {{ $ay.t("Add") }} </span>
          </v-card-title>

          <v-card-text style="height: 500px;">
            <v-list>
              <v-list-item
                v-for="item in availableItems()"
                :key="item.id"
                @click="addItem(item)"
              >
                <v-list-item-title>{{ item.title }}</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-card-text>

          <v-divider></v-divider>
          <v-card-actions>
            <v-btn
              color="primary"
              text
              @click.native="showSelector = false"
              data-cy="dashSelector:cancel"
              >{{ $ay.t("Cancel") }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-col>
    <v-col cols="12" v-if="!hasItems()">
      <v-btn outlined @click.native="showSelector = true">{{
        $ay.t("Add")
      }}</v-btn>
    </v-col>
    <v-col
      v-for="(item, i) in effectiveView"
      :key="i"
      class="d-flex child-flex"
      cols="12"
      sm="6"
      lg="4"
      xl="3"
    >
      <component
        :is="item.type"
        v-bind="item"
        :maxListItems="10"
        v-on:dash-remove="dashRemove"
        v-on:dash-move-start="dashMoveStart"
        v-on:dash-move-back="dashMoveBack"
        v-on:dash-move-forward="dashMoveForward"
        v-on:dash-move-end="dashMoveEnd"
      >
      </component>
    </v-col>
  </v-row>
</template>

<script>
const FORM_KEY = "home-dashboard";
import DashRegistry from "../api/dash-registry";

//---------- DASH ITEMS ----------
import GzDashTestListWidgetsPriciest from "../components/dash-test-list-widgets-priciest.vue";
import GzDashTestBarWidgetCountByUserType from "../components/dash-test-bar-widget-count-by-usertype.vue";
import GzDashTestLineWidgetMonthlyTotalPrice from "../components/dash-test-line-widget-monthly-total-price.vue";
import GzDashTestDayCalendarWidget from "../components/dash-test-day-calendar-widget.vue";

export default {
  components: {
    GzDashTestListWidgetsPriciest,
    GzDashTestBarWidgetCountByUserType,
    GzDashTestLineWidgetMonthlyTotalPrice,
    GzDashTestDayCalendarWidget
  },
  beforeCreate() {
    window.$gz.eventBus.$emit("menu-change", {
      isMain: true,
      icon: "$ayiTachometer",
      title: "Dashboard",
      helpUrl: "form-home-dashboard"
    });
  },
  async created() {
    let vm = this;
    //------------------
    //Test ui feedback mechanisms here:
    //this.formState.errorBoxMessage = "This is a test crlf\r\nOnly a test lf\nEot";

    // await window.$gz.dialog.displayLTModalNotificationMessage(
    //   "ViewServerConfiguration",
    //   "Dashboard",
    //   "success",
    //   "https://www.ayanova.com/subscriptionexpired.htm"
    // );

    // window.$gz.eventBus.$emit(
    //   "notify-error",
    //   "This is a test crlf\r\nOnly a test lf\nEot",
    //   "https://www.ayanova.com/subscriptionexpired.htm"
    // );
    //------------------------
    try {
      //keeping in case need later for some localized text or something
      // await initForm(vm);

      //users have full rights to their dashboard config
      vm.rights = window.$gz.role.fullRightsObject();
      vm.formState.readOnly = false;
      window.$gz.eventBus.$on("menu-click", clickHandler);

      await vm.getDataFromApi();
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        valid: true
      });
      generateMenu(vm);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  methods: {
    hasItems: function() {
      return this.effectiveView && this.effectiveView.length > 0;
    },
    dashMoveStart: function(id) {
      this.move("start", id);
    },
    dashMoveBack: function(id) {
      this.move("left", id);
    },
    dashMoveForward: function(id) {
      this.move("right", id);
    },
    dashMoveEnd: function(id) {
      this.move("end", id);
    },
    dashRemove: function(id) {
      let index = this.getEffectiveViewItemIndexById(id);
      if (index == -1) {
        return;
      }
      this.effectiveView.splice(index, 1);
      this.saveView();
    },
    move: function(direction, id) {
      let index = this.getEffectiveViewItemIndexById(id);
      if (index == -1) {
        return;
      }

      let totalItems = this.effectiveView.length;
      let newIndex = 0;
      //calculate new index
      switch (direction) {
        case "start":
          newIndex = 0;
          break;
        case "left":
          newIndex = index - 1;
          if (newIndex < 0) {
            newIndex = 0;
          }
          break;
        case "right":
          newIndex = index + 1;
          if (newIndex > totalItems - 1) {
            newIndex = totalItems - 1;
          }
          break;
        case "end":
          newIndex = totalItems - 1;
          break;
      }

      this.effectiveView.splice(
        newIndex,
        0,
        this.effectiveView.splice(index, 1)[0]
      );
      this.saveView();
    },
    getEffectiveViewItemIndexById: function(id) {
      return this.effectiveView.findIndex(z => z.id == id);
    },
    addItem: function(item) {
      this.showSelector = false;
      this.effectiveView.push(item);
      this.saveView();
    },
    availableItems: function() {
      let allItems = DashRegistry.availableItems();
      let newItems = allItems.filter(
        z => !this.effectiveView.find(m => m.id == z.id)
      );
      return newItems;
    },
    async getDataFromApi() {
      let vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });

      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.get("dashboard-view");

        if (res.error) {
          //Not found?
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          let savedView = JSON.parse(res.data.view);
          let availableItems = DashRegistry.availableItems();
          let allowedView = savedView.filter(z =>
            availableItems.find(m => m.id == z.id)
          );

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

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });

        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.put(
          "dashboard-view",
          JSON.stringify(vm.effectiveView)
        );

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    }
  },
  data() {
    return {
      effectiveView: [],
      showSelector: false,
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  }
};

/////////////////////////////
//
//
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 "add-dash":
        m.vm.showSelector = true;
        break;

      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiTachometer",
    title: "Dashboard",
    helpUrl: "form-home-dashboard",
    menuItems: []
  };

  menuOptions.menuItems.push({
    title: "Add",
    icon: "$ayiPlus",
    key: FORM_KEY + ":add-dash",
    vm: vm
  });

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

// /////////////////////////////////
// //
// //
// async function initForm(vm) {
//   await fetchTranslatedText(vm);
//   await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY);
//   await populateSelectionLists(vm);
// }

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