import { Component, Watch } from 'vue-property-decorator';
import MicroSchemaConstructor from '@/components/schemas/MicroSchemaConstructor';
import CommonPage from './common-page';
import { DocumentType } from '@typegoose/typegoose';
import { Schema } from '@devsun/arm-bff/dist/lib/database/models/mongo/pgs-schema-util/Schemas';
import { Schema as ESchema } from '@devsun/eva-models';
// @ts-ignore
import VJsonEditor from 'v-jsoneditor';
import get from 'lodash/get';
import { notifyError, notifySuccess } from '@utils/notify';

@Component({
  components: {
    MicroSchemaConstructor,
    VJsonEditor,
  },
})
export default class MSchemaPage extends CommonPage {
  private rawMode = false;
  private schema: ESchema.MetaClassSchemaRaw | null = null;

  @Watch('schemaDoc', { deep: true })
  onSchemaDocChange() {
    this.setSchema();
  }

  get schemaDoc(): DocumentType<Schema> | null {
    const schemaID = this.$route.params.schemaId;

    if (!this.service?.schemas || !schemaID) return null;

    const schemas: Array<DocumentType<Schema>> = JSON.parse(
      this.service.schemas
    );

    return schemas?.find((schemaIt) => schemaIt._id === schemaID) || null;
  }

  mounted() {
    this.setSchema();
  }

  setSchema(): void {
    this.schema = this.schemaDoc?.fgSchema
      ? JSON.parse(this.schemaDoc.fgSchema)
      : null;
  }

  async saveSchema() {
    const schemaFromUI = get(this.$refs, 'msConstructor.currentSchema');
    const schema = this.rawMode ? this.schema : schemaFromUI;

    if (!schema) return;

    if (this.schemaDoc) {
      try {
        // @ts-ignore
        await this.modelerService.updateSchema(this.schemaDoc, schema);

        notifySuccess('Успешно сохранено', 'done_all');
      } catch (err) {
        notifyError('Произошла ошибка при сохранении формы', 'warning');
      }
    }
  }
}
