<template>
  <v-select
    :items="availableRoles"
    item-text="name"
    item-value="id"
    multiple
    chips
    :value="selectedRoles"
    @input="handleInput"
    :readonly="readonly"
    :disabled="disabled"
    :label="label"
    :rules="rules"
    :error-messages="allErrors()"
    :data-cy="!!$ay.dev ? 'roleinput:' + testId : false"
  ></v-select>
</template>
<script>
/*  Xeslint-disable */
export default {
  async created() {
    await window.$gz.enums.fetchEnumList("AuthorizationRoles");
    this.availableRoles = window.$gz.enums.getSelectionList(
      "AuthorizationRoles"
    );
  },
  data() {
    return {
      internalValue: null,
      selectedRoles: [],
      availableRoles: []
    };
  },
  watch: {
    value(val) {
      this.internalValue = val;
      this.setSelectedItems();
    }
  },
  props: {
    label: String,
    rules: Array,
    "error-messages": { type: Array, default: null },
    value: { type: Number, default: 0 },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    error: {
      type: String,
      required: false
    },
    testId: String
  },
  methods: {
    allErrors() {
      let ret = "";
      if (this.error != null) {
        ret = this.error;
      }
      if (this.errorMessages != null && this.errorMessages.length > 0) {
        ret += this.errorMessages.toString();
      }
      return ret;
    },
    setSelectedItems() {
      //turn internalValue numeric bitfield role value into array of selected roles
      let ret = [];
      if (this.internalValue != null && this.internalValue != 0) {
        for (let i = 0; i < this.availableRoles.length; i++) {
          let role = this.availableRoles[i];
          if (!!(this.internalValue & role.id)) {
            ret.push(role.id);
          }
        }
      }
      this.selectedRoles = [...ret];
    },
    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>
