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

import draggable from "vuedraggable";

Vue.component('draggable', draggable);

Vue.component('brick', {
    delimiters: ['<<', '>>'],
    props: {
        'brick': {},
        'parentBrick': {},
        'builder': {
            default: null,
        },
    },
    data: function () {
        return {
            isDragging: false,
            isHovered: false,
            isFlashing: false,
        };
    },
    computed: {
        brickTypeLabel() {
            var brickTypes = this.builder.context.brickTypes;

            var label = brickTypes[this.brick.type].label;
            if (this.brick.type === 'brick.section') {
                this.builder.rootBrick.children.forEach((child, index) => {
                    if (child === this.brick) {
                        label += ' ' + (index + 1);
                    }
                });
            }
            return label;
        }
    },
    methods: {
        isHide: function () {
            return this.brick.type === 'brick.root' || this.brick.type === 'brick.row' || this.brick.type === 'brick.column';
        },
        hasInnerSection: function () {
            return this.brick.isContainer === true || this.brick.preview !== null || this.brick.children.length > 0
        },
        handleDragStart(event) {
            this.isDragging = true;
            EventBus.emitEvent(EventTypes.BRICK_DRAG_START, this, event);
        },
        handleDragEnd(event) {
            this.isDragging = false;
            EventBus.emitEvent(EventTypes.BRICK_DRAG_END, this, event);
        },
        handleDragMove(event, originalEvent) {
            // return EventBus.emitEvent(EventTypes.BRICK_DRAG_MOVE, this, event);
        },
        flash() {
            this.isFlashing = true;
            this.$nextTick(() => {
                zenscroll.intoView(this.$el);
            })
            setTimeout(() => {
                this.isFlashing = false;
            }, 1500);
        },
        isSpecificCol(type) {
            if (this.brick.type !== 'brick.column' || this.parentBrick === null) {
                return false;
            }

            let columnPattern = this.parentBrick.settings.column_pattern;
            let columnPatternParts = {
                '33_66': [4, 8],
                '25_75': [3, 9],
                '66_33': [8, 4],
                '75_25': [9, 3],
                '50_25_25': [6, 3, 3],
                '25_50_25': [3, 6, 3],
                '25_25_50': [3, 3, 6],
                '20_60_20': [2, 8, 2],
            }

            if (!columnPatternParts[columnPattern]) {
                return false;
            }

            let columnIndex = this.parentBrick.children.indexOf(this.brick);

            return columnPatternParts[columnPattern][columnIndex] === type;
        },
        handleUpdated(brick) {
            if (brick.id === this.brick.id) {
                this.brick = brick;

                this.brick.vueComponent = this;
            }
        },
        // edit on double click
        emitUpdate(e) {
            e.preventDefault();
            e.stopPropagation();
            EventBus.emitEvent(EventTypes.BRICK_UPDATE, this);
        },
    },
    created() {
        this.brickTypes = this.builder.context.brickTypes;
    },
    mounted() {
        this.brick.vueComponent = this;// set component ref on tree

        EventBus.$on(EventTypes.BRICK_UPDATED, this.handleUpdated);
    },
    template: `
      <div
          class="brick"
          :class="{
            col: brick.type === 'brick.column',
            'col-2': isSpecificCol(2),
            'col-3': isSpecificCol(3),
            'col-4': isSpecificCol(4),
            'col-6': isSpecificCol(6),
            'col-8': isSpecificCol(8),
            'col-9': isSpecificCol(9),
            'col-12': isSpecificCol(12),
            'no-inner': !hasInnerSection(),
            'is-hide': isHide(),
            hovered: isHovered,
            flash: isFlashing,
          }"
          :data-brick-id="brick.id"
          :data-brick-type="brick.type"
          :data-brick-nature="brick.nature"
          :data-brick-allowed-children="brick.allowedChildren"
          v-on:mouseenter="$emit('mouseenter')"
          v-on:mouseleave="$emit('mouseleave')"
      >
        <div v-if="this.brick.type !== 'brick.row' && this.brick.type !== 'brick.column'"
             v-on:dblclick="emitUpdate"
             class="actions"
        >
          <brick-btn-duplicate :brick="brick"/>

          <!-- separation to align remaining items on the end -->
          <div class="ml-auto mt-auto"></div>
            <brick-btn-template v-if="this.builder.context.isAdmin === true && brick.type === 'brick.section'" :brick="brick"/>
            <brick-btn-layout v-if="brick.type === 'brick.section'" :brick="brick"/>
            <brick-btn-update v-if="brick.hasForm === true" :brick="brick"/>
            <brick-btn-delete :brick="brick"/>
          <div class="title"><< brickTypeLabel >></div>
        </div>

        <div class="inner" v-if="hasInnerSection()">
          <div class="preview" v-if="brick.preview !== null" v-html="brick.preview"></div>
          
          <div v-if="brick.children.length === 0 && this.parentBrick === null" class="text-center text-dark mb-4">
            <h3 class="font-weight-bold">Aucun élément à afficher pour le moment</h3>
            <p>Ajoutez un premier élément pour commencer</p>
            <i class="fa fa-arrow-down"></i>
          </div>

          <draggable
              class="children"
              :class="{ 
                  row: brick.type === 'brick.row', 
                  'drag-receiver': brick.canReceiveCurrentDrag === true, 
              }"
              v-if="brick.isContainer === true"
              v-model="brick.children"
              :group="brick.draggableGroup"
              handle=".actions"
              animation="150"
              @start="handleDragStart"
              @end="handleDragEnd"
              :move="handleDragMove"
          >
            <brick
                v-for="child in brick.children"
                v-bind:key="child.id"
                v-bind:brick="child"
                v-bind:parentBrick="brick"
                :builder="builder"
            ></brick>
          </draggable>

          <brick-btn-add-section
              v-if="this.parentBrick === null && builder && brick.isContainer"
              :brick="brick"
              :builder="builder"
          ></brick-btn-add-section>

          <brick-btn-add
              v-if="this.brick.type === 'brick.column' && builder && brick.isContainer"
              :brick="brick"
              :builder="builder"
          ></brick-btn-add>
        </div>
      </div>
    `,
});