<template>
  <widget-wrapper
    v-bind="$props"
    v-show="currentValue !== null"
    class="q-my-md"
  >
    <base-label-value :padded-label="paddedGroups">
      <template v-slot:label>
        {{ fieldNode.label ? fieldNode.label : '' }}
      </template>
      <template v-slot:value>
        <span>{{ currentValue ? 'Да' : 'нет' }}</span>
      </template>
    </base-label-value>
  </widget-wrapper>
</template>

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

enum ValidBoolTypes {
  string = 'string',
  number = 'number',
  boolean = 'boolean',
}

@Component({
  components: {
    QCheckbox,
    QTooltip,
    WidgetWrapper,
  },
})
export default class CheckboxText extends Vue {
  @Prop({}) paddedGroups!: boolean;
  @Prop() fieldNode: FormGeneratorNode;
  @Prop() value: ObjectMetaModelValue;

  private static bools = {
    [ValidBoolTypes.string]: {
      true: true,
      false: false,
    },
    [ValidBoolTypes.number]: {
      0: false,
      1: true,
    },
  };

  private static getBool(type: ValidBoolTypes, value: any): boolean | null {
    if (type === ValidBoolTypes.boolean) {
      return value as boolean;
    }

    const res = CheckboxText.bools[type]
      ? CheckboxText.bools[type][value.toString()]
      : null;
    return res !== void 0 ? res : null;
  }

  private get currentValue(): boolean | null {
    return CheckboxText.getBool(
      this.getBoolTypeByValue(this.value),
      this.value.__id
    );
  }

  getBoolTypeByValue(value: ObjectMetaModelValue) {
    switch (typeof value.__id) {
      case 'string':
        return ValidBoolTypes.string;
      case 'number':
        return ValidBoolTypes.number;
      case 'boolean':
        return ValidBoolTypes.boolean;
      default:
        throw new Error(
          `wrong type specified for CheckboxText boolean for '${this.fieldNode.fieldName}' `
        );
    }
  }
}
</script>
