<template>
  <widget-wrapper v-bind="$props" v-show="currentValue">
    <div>
      <base-label-value
        :key="val.key"
        v-for="val in currentValue"
        :padded-label="paddedGroups"
      >
        <template v-slot:label>
          {{ val.key }}
        </template>
        <template v-slot:value>
          {{ val.value }}
        </template>
      </base-label-value>
    </div>
  </widget-wrapper>
</template>

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

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

  @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 as string) : '';
  }

  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
    }
  }
}
</script>
