<template>
  <v-select
    :items="availableRoles"
    item-text="name"
    item-value="id"
    multiple
    chips
    deletable-chips
    :value="selectedValue"
    :readonly="readonly"
    :disabled="disabled"
    :label="label"
    :rules="rules"
    :error-messages="errorMessages"
    :data-cy="'roleinput:' + testId"
    @input="handleInput"
  ></v-select>
</template>
<script>
export default {
  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 }
  },
  data() {
    return {
      internalValue: null,
      availableRoles: []
    };
  },
  computed: {
    selectedValue() {
      const ret = [];
      if (this.value != null && this.value != 0) {
        for (let i = 0; i < this.availableRoles.length; i++) {
          const role = this.availableRoles[i];
          if (this.value & role.id) {
            ret.push(role.id);
          }
        }
      }
      return ret;
    }
  },
  async created() {
    await window.$gz.enums.fetchEnumList("AuthorizationRoles");
    const rawRoles = window.$gz.enums.getSelectionList("AuthorizationRoles");
    if (this.limitSelectionTo == null) {
      this.availableRoles = rawRoles;
    } else {
      if (this.limitSelectionTo == "inside") {
        //CustomerRestricted=2048, Customer=4096
        this.availableRoles = rawRoles.filter(
          z => z.id != 2048 && z.id != 4096
        );
      } else {
        this.availableRoles = rawRoles.filter(
          z => z.id == 2048 || z.id == 4096
        );
      }
    }
  },
  methods: {
    handleInput(value) {
      let newValue = 0;
      if (value != null && value != [] && value.length > 0) {
        for (let i = 0; i < value.length; i++) {
          const role = value[i];
          newValue = newValue | role;
        }
      }
      this.$emit("input", newValue);
    }
  }
};
</script>
