<script>
import {castId, keyBy, objCopy, isEmpty} from "../utils";
import forEach from "lodash-es/forEach";
import axios from "axios";

export default {
  props: ['model_id', 'schema', 'objects'],
  name: "NewObjectForm",
  data() {
    const model = this.schema.obj_models.find((m) => m.id === this.model_id);
    let properties = this.schema.prop_models.filter((m) => m.object === model.id);
    let relations = this.schema.rel_models.filter((m) => m.object === model.id);

    properties.sort((a, b) => a.name.localeCompare(b.name));
    relations.sort((a, b) => a.name.localeCompare(b.name));

    let values = {};
    properties.forEach((p) => {
      if (p.optional) {
        values[p.id] = [];
      } else {
        values[p.id] = [objCopy(p.default)];
      }
    });

    properties = keyBy(properties, 'id');
    relations = keyBy(relations, 'id');

    let model_names = {};
    this.schema.obj_models.forEach((m) => {
      model_names[m.id] = m.name;
    });

    return {
      model,
      properties,
      relations,
      haveRelations: !isEmpty(relations),
      model_names,
      values,
      name: '',
      relationRefs: [],
    }
  },
  methods: {
    /** Get values in the raw format without grouping */
    collectData() {
      if (isEmpty(this.name)) {
        throw new Error("Name is required");
      }

      let values = [];
      forEach(objCopy(this.values), (vv, k) => {
        for (let v of vv) {
          values.push({
            model_id: castId(k),
            value: v
          })
        }
      })

      let relations = [];
      for (let rref of this.relationRefs) {
        for (let r of rref.collectData()) {
          relations.push(r);
        }
      }

      return {
        model_id: this.model_id, // string is fine
        name: this.name,
        values,
        relations,
      };
    },

    trySave() {
      let data;
      try {
        data = this.collectData();
      } catch (e) {
        alert(e.message);
        return;
      }
      console.log('Try save', data);

      axios({
        method: 'post',
        url: '/object/create',
        data: data
      })
      .then(function (response) {
        location.href = '/objects';
      })
      .catch(function (error) {
        // TODO show error toast instead
        alert(error.response ?
            error.response.data :
            error)
      });
    },

    setRelationRef(el) {
      if (el) {
        this.relationRefs.push(el)
      }
    },
  },
  beforeUpdate() {
    this.relationRefs = []
  },
  mounted() {
    this.$el.parentNode
        .classList.add('EditForm');
  }
}
</script>

<template>
  <h2>New {{ model.name }}</h2>

  <p><input type="button" value="Save" @click="trySave"></p>

  <table>
    <tr>
      <th><label for="field-name">Name</label></th>
      <td>
         <input type="text" id="field-name" v-model="name">
      </td>
    </tr>

    <property v-for="(property, pi) in properties" :model="property" :values="values[property.id]" :key="pi"></property>
  </table>

  <div v-if="haveRelations">
    <h3>Relations</h3>

    <new-relation
        v-for="relation in relations"
        :ref="setRelationRef"
        :model_id="relation.id"
        :objects="objects"
        :schema="schema"
    ></new-relation>
  </div>
</template>
