import Vue from 'vue/dist/vue'
import TreeHandler from "../util/TreeHandler";

if (document.querySelector('#brick-builder-app')) {
    window.vueBuilderApp = new Vue({
        delimiters: ['<<', '>>'],
        el: '#brick-builder-app',
        props: {
            'rootBrickId': {
                default: null,
            },
            'rootBrick': {
                default: null,
            },
            'builderDataUrl': {
                default: null,
            },
            'context': {
                default: null,
            },
        },
        data: {
            loader: null,
            loaded: false,
        },
        mounted: function () {
            if (typeof this.$el.parentElement === 'undefined' || this.$el.parentElement === null) {
                return;
            }
            this.rootBrickId = this.$el.getAttribute('data-root-brick-id');
            this.builderDataUrl = this.$el.getAttribute('data-builder-data-url');
            this.previewUrl = this.$el.getAttribute('data-builder-preview-url');
            this.loader = document.querySelector('body').getAttribute('data-loader');
            // `this` est une référence à l'instance de vm
            //TODO: initialize through api https://codesandbox.io/s/github/vuejs/vuejs.org/tree/master/src/v2/examples/vue-20-component-blog-post-example?file=/index.html:197-320
            fetch(this.builderDataUrl)
                .then((response) => {
                    return response.json();
                })
                .then((data) => {
                    var tree = data.rootBrick;
                    tree = TreeHandler.prepareTree(tree);
                    this.rootBrick = tree;
                    this.context = {
                        categories: data.categories,
                        brickTypes: data.brickTypes,
                        isAdmin: data.isAdmin,
                        loader: this.loader,
                        previewUrl: this.previewUrl,
                    };
                    this.loaded = true;
                })
            ;
        },
    });
}
