<template>
  <v-select
    dense
    :items="daysOfWeek"
    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="'dayinput:' + testId"
    @input="handleInput"
  ></v-select>
</template>
<script>
//bitwise selection of days of week
//https://stackoverflow.com/a/24174625/8939

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 },
    testId: { type: String, default: null }
  },
  data() {
    return {
      internalValue: null,
      daysOfWeek: []
    };
  },
  computed: {
    selectedValue() {
      const ret = [];
      if (this.value != null && this.value != 0) {
        for (let i = 0; i < this.daysOfWeek.length; i++) {
          const day = this.daysOfWeek[i];
          if (this.value & day.id) {
            ret.push(day.id);
          }
        }
      }
      return ret;
    }
  },
  async created() {
    await window.$gz.enums.fetchEnumList("AyaDaysOfWeek");
    this.daysOfWeek = window.$gz.enums.getSelectionList("AyaDaysOfWeek", true);
  },
  methods: {
    handleInput(value) {
      let newValue = 0;
      if (value != null && value != [] && value.length > 0) {
        for (let i = 0; i < value.length; i++) {
          const day = value[i];
          newValue = newValue | day;
        }
      }
      this.$emit("input", newValue);
    }
  }
};
</script>
