<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          {{ toUsers }}
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          <v-row cols="12">
            <v-col cols="9">
              <gz-pick-list
                :ayaType="ayaTypes().User"
                :showEditIcon="false"
                v-model="pickListSelectedUserId"
                :label="$ay.t('UserList')"
                ref="userPickList"
                @input="checkSave()"
              ></gz-pick-list> </v-col
            ><v-col cols="1">
              <v-btn @click="addSelected()">
                <v-icon>fa-plus</v-icon>
              </v-btn>
            </v-col>
          </v-row>

          <v-col cols="12">
            <template v-for="item in toUsers">
              <v-chip
                color="primary"
                outlined
                :key="item.id"
                class="ma-2"
                close
                @click:close="closeChip(item)"
              >
                {{ item.name }}
              </v-chip>
            </template>
          </v-col>

          <v-col cols="12">
            <v-textarea
              v-model="message"
              :label="$ay.t('MemoMessage')"
              ref="message"
              auto-grow
              :clearable="!formState.readOnly"
              @input="checkSave()"
            ></v-textarea>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

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

const FORM_KEY = "home-notify-direct";

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

      vm.rights = window.$gz.role.fullRightsObject();
      generateMenu(vm);

      vm.formState.ready = true;
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        valid: true,
        loading: false,
        readOnly: false
      });
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //-------------

      //------------------
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      pickListSelectedUserId: null,
      items: [],
      toUsers: [],
      message: null,
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject()
    };
  },
  //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: {
    checkSave() {
      let hasSelection =
        this.toUsers.length > 0 ||
        (this.pickListSelectedUserId != null &&
          this.pickListSelectedUserId != 0);
      let hasText = this.message != null && this.message != "";

      this.formState.dirty = hasSelection && hasText;
      if (this.canSave) {
        window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
      } else {
        window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
      }
    },
    closeChip(item) {
      // console.log(item);
      // debugger;
      let i = this.toUsers.findIndex(z => z.id == item.id);
      if (i != -1) {
        this.toUsers.splice(i, 1);
      }
      this.checkSave();
    },
    addSelected() {
      let selected = this.$refs.userPickList.getFullSelectionValue();
      if (selected == null) {
        return;
      }
      //already in the list?
      if (this.toUsers.find(z => z.id == selected.id)) {
        return;
      }

      this.toUsers.push(selected);
      this.pickListSelectedUserId = 0;
      this.checkSave();
    },
    ayaTypes: function() {
      return window.$gz.type;
    },

    form() {
      return window.$gz.form;
    },

    async submit() {
      let vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;

        //always submit from this form for the current logged in user id
        let url = "notify/direct-message";

        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        try {
          let userIdList = [];
          if (vm.toUsers.length > 0) {
            vm.toUsers.forEach(z => {
              userIdList.push(z.id);
            });
          } else {
            //just accept the single userid in the pickLkist
            userIdList.push(vm.pickListSelectedUserId);
          }
          let res = await window.$gz.api.upsert(url, {
            users: userIdList,
            message: this.message
          });

          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            vm.pickListSelectedUserId = null;
            vm.items = [];
            vm.toUsers = [];
            vm.message = null;
            //Only a post, no data returned
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false
            });
            vm.checkSave();
          }
        } catch (error) {
          window.$gz.errorHandler.handleFormError(error, vm);
        } finally {
          vm.loading = false;
        }
      }
    }
  }
};

/////////////////////////////
//
//
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;

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

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-comment-alt",
    title: "DirectNotification",
    helpUrl: "form-home-notify-direct",

    menuItems: []
  };

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

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

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  console.log("userIdList is ", vm.$route.params.userIdList);
  if (vm.$route.params.userIdList != undefined) {
    //userIdList is  1,2,3,4
    await preFillSelection(vm);
  }
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "DirectNotification",
    "UserList",
    "MemoMessage",
    "MemoToID"
  ]);
}

//////////////////////////////////////////////////////////
//
// Pre fill if pre-selected users
//
async function preFillSelection(vm) {
  //iterate the list
  //vm.$route.params.userIdList;
  // let temp = new Array();
  // temp = vm.$route.params.userIdList.split(",");
  // for (a in temp) {
  //   temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
  // }

  let t = vm.$route.params.userIdList.split(",").map(z => parseInt(z, 10));
  console.log("Prefill selection array is", t);
}
</script>
