<template>
  <FormGeneratorWrapper :model="model" mode="create" :schema="schema" />
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import FormGeneratorWrapper from '@components/common/node-generator/FormGeneratorWrapper.vue';

const PREVIEW_SDD = `Sdd_previewSdd`;
const EDIT_SDD = `Sdd_editSdd`;

@Component({
  components: { FormGeneratorWrapper },
})
export default class SddConstructor extends Vue {
  @Prop() model: any;
  @Prop() editMod: boolean;

  isIncomesString = false;
  schema = {};

  @Watch('model', { immediate: true })
  changeModel(model: any): void {
    if (model) {
      this.getSchema(this.editMod);
    }
  }

  @Watch('editMod')
  async getSchema(currentEditMode: boolean) {
    this.livingWageIncomesToArray(currentEditMode, this.model.livingWage.incomes);

    this.schema = await this.$store
      .dispatch('utils/components/fetchModelByCode', this.schemaCode)
      .catch(() => {
        console.warn(`Couldn't get schema ${this.schemaCode} `);
      });
  }

  get schemaCode() {
    return this.editMod ? EDIT_SDD : PREVIEW_SDD;
  }

  livingWageIncomesToArray(currentEditMode: boolean, incomes: any) {
    const isIncomesString = typeof incomes === 'string';
    if (!isIncomesString && !currentEditMode && incomes) {
      this.model.livingWage.incomes = Object.values(incomes);
    }
  }
}
</script>
