<template>
  <widget-wrapper v-bind="$props" v-show="!isHidden">
    <div class="q-my-md">
      <base-label-value :padded-label="paddedGroups">
        <template v-slot:label>
          {{ fieldNode.label ? fieldNode.label : '' }}
        </template>
        <template v-slot:value>
          <div v-for="val in currentValue">{{ val }}</div>
        </template>
      </base-label-value>
    </div>
  </widget-wrapper>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import {
  WidgetWrapper,
  createIMaskTokens,
  ObjectMetaModelValue,
} from '@devsun/form-generator/dist';
import { Field } from '@devsun/eva-models';
import { FormGeneratorNode } from '@devsun/form-generator';

@Component({
  components: {
    WidgetWrapper,
  },
})
export default class CardString extends Vue {
  @Prop({ required: true }) value: ObjectMetaModelValue;
  @Prop() fieldNode: FormGeneratorNode;

  @Prop({}) hideNulls!: boolean;
  @Prop({}) paddedGroups!: boolean;

  private fieldMask = null;

  // todo apply reference book on some scheme param?

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

  get currentValue(): string[] {
    if (this.value && Array.isArray(this.value.__id)) {
      return this.value.__id;
    }
    return this.value ? [this.value.__id] : [''];
  }

  get maskedValue() {
    if (this.fieldMask) {
      return this.fieldMask.resolve(this.value);
    }
    return this.value;
  }

  get maskConfig() {
    if (this.fieldNode.masks && this.fieldNode.masks.length > 0) {
      // get the last (top) one
      // IMask has one missing feature - ability to set placeholder char for every char in definition
      return {
        definitions: createIMaskTokens(),
        mask: this.fieldNode.masks[this.fieldNode.masks.length - 1].value,
        lazy: false,
      };
    } else {
      return null;
    }
  }

  emitInput(cb, value) {
    if (this.fieldMask) {
      this.fieldMask.resolve(value);
      cb(this.fieldMask.unmaskedValue);
    } else {
      cb(value);
    }
  }

  async created() {
    if (this.maskConfig) {
      // you can create mask like this - createMask(this.maskConfig)
      // turned off since it does not perform what's required
    }
  }

  get isHidden(): boolean {
    return (
      this.hideNulls && (!this.currentValue || !this.currentValue.some(Boolean))
    );
  }
}
</script>
