<template>
  <div class="editor" v-if="item">
    <!-- Custom editor (C# CmsPageVersion or CmsItem (SingleTonItem) with CustomEditor attribute), else fallback to default 'schema-editor' -->
    <slot></slot>
    <component :is="schema.format || $options.components.schemaEditor" v-model="item" :schema="schema"></component>
  </div>
</template>

<style lang="scss" scoped>
.editor {
  &::after {
    content: ' ';
    display: block;
    clear: both;
  }
}
</style>

<script>
import schemaEditor from '../schema/schema-editor.vue';
import { PermissionTypes } from '../stores/types/PermissionStoreModel';

export default {
  docs: `Kiest het juiste component op basis van het CustomEditor attribuut voor een CmsPageVersion of CmsItem (SingletonItem).`,
  props: {
    item: {
      type: Object,
      required: true
    },
    schema: {
      type: Object,
      required: true,
      docs: `JSON schema object`
    }
  },
  components: {
    schemaEditor
  },

  created() {
    this.checkEntityPermissions();
  },

  methods: {
    setReadOnlyState(object, isReadOnly) {
      for (const key in object) {
        if (typeof object[key] !== 'object' || object[key] === null || Object.keys(object[key]).length === 0) {
          if (key === 'isReadOnlySet') {
            if (object[key] === false) {
              this.$set(object, 'isReadOnly', isReadOnly);
            }
          }

          continue;
        }

        if (Array.isArray(object[key])) {
          const newArray = [];
          for (let i = 0; i < object[key].length; i++) {
            newArray.push(this.setReadOnlyState(object[key][i], isReadOnly));
          }
          this.$set(object, key, newArray);
        } else {
          this.$set(object, key, this.setReadOnlyState(object[key], isReadOnly));
        }
      }

      return object;
    },

    checkEntityPermissions() {
      // So what is going on here? The schema per type is only loaded once, not for every item. But the permissions do no longer
      // only apply to type level, but also entity level. Meaning you have permission to read the type products but only to edit
      // the few you own. Therefore we dynamically change the schema based on the permission you have for the current entity.
      // We remember the default value so that we can honor readonly attributes set on models or other customizations made on schema.
      // We use VUE to set properties so that they will be reactive.
      // Important: this also works for custom editors

      const isNew = !(this.item && this.item.id);

      if (isNew) {
        // Ignore when adding new items. If you do not have permissions to create items you should not get here.
        return;
      }

      const readOnly = !this.$store.getters['permissions/permissionAllows'](PermissionTypes.Update, this.item);
      this.schema = this.setReadOnlyState(this.schema, readOnly);
    }
  }
};
</script>
