import Vue from 'vue/dist/vue'
import EventBus from "../util/EventBus";
import EventTypes from "../util/EventTypes";

Vue.component('brick-btn-add', {
    delimiters: ['<<', '>>'],
    props: [
        'brick',
        'builder',
    ],
    data: function () {
        return {
            visible: false,
            inverted: false,
            selectedTab: 0,
            selectedBrickType: null,
            processedCategories: [],
            isLoading: false,
            width: 0,
            left: 0,
            top: 0,
        };
    },
    methods: {
        brickTypeLabel(type) {
            var brickTypes = this.builder.context.brickTypes;
            if (brickTypes[type] && brickTypes[type].label) {
                type = brickTypes[type].label
            }
            return type;
        },
        brickTypeIcon(type) {
            var brickTypes = this.builder.context.brickTypes;
            var icon = `<i class="far fa-image-slash"></i>`;

            if (brickTypes[type] && brickTypes[type].icon) {
                icon = `<img src="${brickTypes[type].icon}" alt="${brickTypes[type].label}" height="60" />`
            }

            return icon;
        },
        show: function () {
            this.visible = true;

            let brickBuilderApp = document.querySelector('#brick-builder-app');

            this.width = brickBuilderApp.offsetWidth * 0.85; // 85% of the app width
            this.left = brickBuilderApp.getBoundingClientRect().left + (brickBuilderApp.offsetWidth - this.width) / 2;
            this.top = this.$el.getBoundingClientRect().top;
            this.top += 30;

            let maxHeight = document.documentElement.offsetHeight - 500;
            if (this.top > maxHeight) {
                this.top = maxHeight;
            }

            document.addEventListener('scroll', this.onScroll);

            this.inverted = this.brick.isContainer && this.brick.type !== 'brick.column';
        },
        hide: function () {
            this.visible = false;
        },
        toggle: function () {
            this.visible = !this.visible;
        },
        beginLoading: function () {
            this.isLoading = true;
        },
        onScroll: function () {
            this.top = this.$el.getBoundingClientRect().top;
            this.top += 30;

            let maxHeight = document.documentElement.offsetHeight - 400;
            if (this.top > maxHeight) {
                this.top = maxHeight;
            }

            if (this.top < 0) {
                this.top = 10;
            }
        },
        finishLoading: function () {
            this.isLoading = false;
        },
        changeTab: function (index) {
            this.selectedTab = index;
        },
        processCategories(categories) {
            if (!this.brick) {
                return [];
            }
            // break vue "reactive" behavior, we want to work with a copied object
            categories = JSON.parse(JSON.stringify(categories));
            var allowedChildren = this.brick.allowedChildren;
            var cats = {};
            Object.keys(categories).forEach((k) => {
                if (categories[k].types.length > 0) {
                    var cat = categories[k];
                    var indexesToDelete = [];

                    var atLeastOneFound = false;
                    for (var index = 0; index < cat.types.length; index++) {
                        var type = cat.types[index];
                        if (allowedChildren.indexOf(type) === -1) {
                            indexesToDelete.push(index);
                        } else {
                            atLeastOneFound = true;
                        }
                    }

                    indexesToDelete.reverse().forEach((index) => Vue.delete(cat.types, index))

                    if (cat.types.length > 0 && atLeastOneFound === true) {
                        cats[k] = cat;
                    }
                }


            });
            return cats;
        },
        emit(brickType) {
            this.selectedBrickType = brickType
            EventBus.emitEvent(EventTypes.BRICK_ADD, this);
        }
    },

    created: function () {
        this.processedCategories = this.processCategories(this.builder.context.categories);
        var catArray = Object.values(this.processedCategories);
        if (catArray.length === 1 && catArray[0].types.length === 1) {
            this.selectedBrickType = Object.values(catArray[0].types)[0];
        }
    },

    template: `
      <div class="brick-add">
        <div
          class="d-flex p-2 rounded border-dashed"
          :class="{
            active: visible,
          }"
        >
          <button
              v-on:click="show()"
              class="btn btn-sm brick-action d-block text-center w-100"
          >
            <i class="fa fa-plus"></i>
          </button>
        </div>
        <div
            v-bind:class="{opened: visible, inverted: inverted,}"
            class="add-brick-widget"
        >
          <div class="close-overlay">
              <div class="inner flex-column" :style="'width: ' + width + 'px; left: ' + left + 'px; top: ' + top + 'px'">
                <div class="brick-add-header mb-4 d-flex">
                  <div class="title">Insérer une brique</div>
                  <button
                      class="btn btn-secondary"
                      @click="hide()"
                  >
                    <i class="fa fa-close"></i>
                  </button>
                </div>
                <div v-if="this.isLoading" v-html="this.builder.context.loader" ></div>
                <div v-if="!this.isLoading" class="brick-cat-tabs">
                  <div class="btn-group">
                    <button
                        v-for="(config, cat, index) in processedCategories"
                        v-show="config.types.length > 0"
                        class="btn"
                        v-on:click="changeTab(index)"
                        :title="config.label"
                        :class="{
                              selected: selectedTab === index,
                          }"
                        v-html="config.label"
                    ></button>
                  </div>
                  <div class="brick-cat-contents">
                    <ul class="list-unstyled">
                      <li
                          v-for="(config, cat, index) in processedCategories"
                      >
                        <div
                            v-show="config.types.length > 0"
                            class="brick-cat-content mt-4"
                            :class="{
                                  selected: selectedTab === index,
                              }"
                            :data-brick-cat="cat"
                        >
                          <div class="brick-types">
                            <button
                                v-for="brickType in config.types"
                                class="brick-type btn"
                                :data-brick-type="brickType"
                                v-on:click="emit(brickType)"
                                :title="brickTypeLabel(brickType)"
                            ><span v-html="brickTypeIcon(brickType)"></span><< brickTypeLabel(brickType) >></button>
                          </div>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
          </div>
        </div>
      </div>
    `,
});
