<template>
  <widget-wrapper v-bind="$props" ref="widget">
    <q-input
      :label="
        fieldNode.label ? fieldNode.label + (i ? ' #' + (i + 1) : '') : ''
      "
      v-for="(_, i) in values"
      :key="i"
      autogrow
      bottom-slots
      outlined
      filled
      v-bind="props"
      :type="inputType"
      :readonly="isReadonly"
      v-model="values[i]"
    >
      <template v-slot:append v-if="!isReadonly">
        <q-btn
          v-show="values.length !== 1"
          round
          dense
          flat
          icon="close"
          @click="remove(i)"
        >
          <q-tooltip> Удалить</q-tooltip>
        </q-btn>
        <q-btn
          v-show="i === values.length - 1"
          round
          dense
          flat
          icon="add"
          @click="add"
        >
          <q-tooltip> Добавить</q-tooltip>
        </q-btn>
      </template>
    </q-input>

    <div v-if="hasError">
      {{ errorMessage }}
    </div>
  </widget-wrapper>
</template>

<script lang="ts">
import { Component, Watch } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import { Field } from '@devsun/eva-models';
import isEqual from 'lodash/isEqual';
import {
  FormWidget,
  WidgetWrapper,
  ValidatedField,
  SubscriberWidget,
} from '@devsun/form-generator/dist';

@Component({
  components: {
    WidgetWrapper,
  },
})
export default class StringInputList extends mixins(
  SubscriberWidget,
  ValidatedField,
  FormWidget
) {
  protected get props() {
    return this.fieldNode?.rawAttrs?.props || undefined;
  }

  @Watch('values', { deep: true })
  protected input(values, prev) {
    if (values.length === 1 && prev == values[0] && !prev) return;
    this.$refs.widget.inputEvents?.input(values.slice());
  }

  protected remove(i) {
    this.values.splice(i, 1);
  }

  protected add() {
    this.values.push('');
  }

  get isReadonly(): boolean {
    if (this.fieldNode.simlink) {
      return true;
    }
    return this.fieldNode.readonly;
  }

  get inputType(): string {
    switch (this.fieldNode.rawAttrs.view) {
      case Field.View.textarea:
        return 'textarea';
      default:
        return 'text';
    }
  }

  @Watch('value', { deep: true, immediate: true })
  valueUpdated(value) {
    // todo const values = value.__id + add default empty input (validation is broken here)
    const values = value
      ? Array.isArray(value.__id)
        ? value.__id.slice()
        : [value.__id]
      : [];
    if (!isEqual(values, this.values)) this.values = values;
  }

  protected values = [];
}
</script>
