<template>
  <v-select
    :items="availableRoles"
    item-text="name"
    item-value="id"
    multiple
    chips
    deletable-chips
    :value="selectedValue"
    @input="handleInput"
    :readonly="readonly"
    :disabled="disabled"
    :label="label"
    :rules="rules"
    :error-messages="errorMessages"
    :data-cy="'roleinput:' + testId"
  ></v-select>
</template>
<script>
/*  Xeslint-disable */
export default {
  async created() {
    await window.$gz.enums.fetchEnumList("AuthorizationRoles");
    let rawRoles = window.$gz.enums.getSelectionList("AuthorizationRoles");
    if (this.limitSelectionTo == null) {
      this.availableRoles = rawRoles;
    } else {
      if (this.limitSelectionTo == "inside") {
        //CustomerLimited=2048, CustomerFull=4096
        this.availableRoles = rawRoles.filter(
          z => z.id != 2048 && z.id != 4096
        );
      } else {
        this.availableRoles = rawRoles.filter(
          z => z.id == 2048 || z.id == 4096
        );
      }
    }
  },
  data() {
    return {
      internalValue: null,
      availableRoles: []
    };
  },
  props: {
    label: { type: String, default: null },
    rules: { type: Array, default: undefined },
    errorMessages: { type: Array, default: null },
    value: { type: Number, default: 0 },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    limitSelectionTo: { type: String, default: null }, //"inside" - no customer roles, "outside" - no non-customer roles
    testId: { type: String, default: null }
  },
  computed: {
    selectedValue() {
      let ret = [];
      if (this.value != null && this.value != 0) {
        for (let i = 0; i < this.availableRoles.length; i++) {
          let role = this.availableRoles[i];
          if (!!(this.value & role.id)) {
            ret.push(role.id);
          }
        }
      }
      return ret;
    }
  },
  methods: {
    handleInput(value) {
      let newValue = 0;
      if (value != null && value != [] && value.length > 0) {
        for (let i = 0; i < value.length; i++) {
          let role = value[i];
          newValue = newValue | role;
        }
      }
      this.$emit("input", newValue);
    }
  }
};
</script>
