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) {
                console.log('No cms builder to initialize. Aborting.');
                return;
            }
            console.log('APP INIT');
            console.log(this.$el);
            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
            console.log('vue created: ')
            console.log(this)
            //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);
                    console.log('prepared brick tree: ');
                    console.log(tree);
                    this.rootBrick = tree;
                    this.context = {
                        categories: data.categories,
                        brickTypes: data.brickTypes,
                        isAdmin: data.isAdmin,
                        loader: this.loader,
                        previewUrl: this.previewUrl,
                    };
                    console.log('prepared context:');
                    console.log(this.context);
                    this.loaded = true;
                })
            ;
        },
    });
}