import { mixins } from 'vue-class-component';
import { Component, Prop } from 'vue-property-decorator';
import {
  ValidatedField,
  SubscriberWidget,
  ObjectMetaModel,
  ObjectMetaModelValue,
} from '@devsun/form-generator/dist';
import FormGeneratorWrapper from '@components/common/node-generator/FormGeneratorWrapper.vue';
import { Meta, Model, Schema } from '@devsun/eva-models';
import { FormGeneratorNode } from '@devsun/form-generator';
import get from 'lodash/get';

@Component({
  components: {
    FormGeneratorWrapper,
  },
})
export default class NestedFormGenerator extends mixins(
  SubscriberWidget,
  ValidatedField
) {
  @Prop({ required: true }) value!: ObjectMetaModelValue;
  @Prop() model!: ObjectMetaModel;
  @Prop() fieldNode: FormGeneratorNode;
  @Prop({}) showIndexes?: boolean;
  @Prop({}) labelTemplate?: string;
  @Prop({}) level: number;
  @Prop({}) rootLevel: number;

  get values(): Model.Base[] | undefined {
    const value = this.value?.__id;

    if (value) {
      return Array.isArray(value) ? value : [value];
    }
  }

  get reference(): Meta.Reference | undefined {
    return this.fieldNode?.reference;
  }

  get show(): boolean {
    return Boolean(
      this.values &&
        this.values.every((value) => typeof value === 'object') &&
        this.schema
    );
  }

  get linkedSchemas(): Schema.LinkedSchemaMap {
    return get(this.fieldNode, 'rootSchema.schema.linkedSchema');
  }

  get schema(): Partial<Schema.MetaClassSchemaRaw> | undefined {
    if (!this.reference) return;

    return get(
      this.linkedSchemas,
      `${this.reference.service}.${this.reference.entity}`
    );
  }

  get attractionCode(): string | undefined {
    return this.schema?.name;
  }
}
