/**
 * @module package/quiqqer/template-tailwindcss/bin/Controls/Children/SiteListPreview
 * @author www.pcsg.de (Michael Danielczok)
 */
define('package/quiqqer/template-tailwindcss/bin/Controls/Children/SiteListPreview', [

    'qui/QUI',
    'qui/controls/Control'

], function (QUI, QUIControl) {
    "use strict";

    return new Class({

        Extends: QUIControl,
        Type   : 'package/quiqqer/template-tailwindcss/bin/Controls/Children/SiteListPreview',

        Binds  : [
            'toggle',
            'mouseEnterEvent',
            'mouseLeaveEvent'
        ],
        options: {
            previewwidth : 550,
            openaction   : 'click', // 'click', 'hover'
            opendirection: 'left' // 'left' = control is placed in right sidebar, 'right' = control is placed in left sidebar
        },

        initialize: function (options) {
            this.parent(options);

            this.active       = 0;
            this.activeEntry  = null;
            this.$right       = null;
            this.$left        = null;
            this.$top         = 0;
            this.$width       = 0;
            this.windowWidth  = 0;
            this.controlWidth = 0;
            this.controlPos   = 0; // left corner pos

            QUI.addEvent('resize', function () {
                this.calcSizes();
                this.$resize();
            }.bind(this));

            this.addEvents({
                onImport: this.$onImport
            });
        },

        /**
         * event : on import
         */
        $onImport: function () {
            var self = this;

            this.$Elm         = this.getElm();
            this.entries      = this.$Elm.getElements('article');
            this.previews     = this.$Elm.getElements('.qui-control-preview');
            this.$width       = this.getAttribute('previewwidth').toInt();
            this.windowWidth  = QUI.getWindowSize().x;
            this.controlWidth = this.getElm().getSize().x;
            this.controlPos   = this.getElm().getPosition().x;


            if (!this.entries || this.entries.length < 1 ||
                !this.previews || this.previews.length < 1) {
                return;
            }

            this.calcSizes();
            this.$resize();

            this.previews.forEach(function (Preview) {
                var Close = Preview.getElement('.qui-control-preview-close');

                if (Close) {
                    Close.addEvent('click', function () {
                        self.hide(Preview);
                    });
                }
            });

            this.previews.addEvent('click', function (event) {
                event.stopPropagation();
            });
        },

        /**
         * Resize
         */
        $resize: function () {
            if (this.getAttribute('openaction') === 'click') {
                this.entries.addEvent('click', this.toggle);
                return;
            }

            // hover effect need special treatment for mobile and desktop
            if (QUI.getWindowSize().x > 767) {
                this.entries.removeEvent('click', this.toggle);
                this.entries.addEvent('mouseenter', this.mouseEnterEvent);
                this.entries.addEvent('mouseleave', this.mouseLeaveEvent);
                return;
            }

            this.entries.removeEvent('mouseenter', this.mouseEnterEvent);
            this.entries.removeEvent('mouseleave', this.mouseLeaveEvent);
            this.entries.addEvent('click', this.toggle);
        },

        /**
         * Toggle preview
         *
         * @param event
         */
        toggle: function (event) {
            var Target = event.target;

            if (Target.nodeName !== 'ARTICLE') {
                Target = Target.getParent('article')
            }

            var self            = this,
                LastActiveEntry = this.$Elm.getElement('article.active'),
                Preview         = Target.getElement('.qui-control-preview');

            // close active
            if (Target.hasClass('active')) {
                this.hide(Preview).then(function () {
                    LastActiveEntry.removeClass('active');
                });

                return;
            }

            if (!LastActiveEntry) {
                this.show(Preview).then(function () {
                    Target.addClass('active');
                });

                return;
            }

            var LastActivePreview = LastActiveEntry.getElement('.qui-control-preview');

            this.hide(LastActivePreview).then(function () {
                LastActiveEntry.removeClass('active');
                self.show(Preview);
            }).then(function () {
                Target.addClass('active');
            });
        },

        /**
         * Hide site preview
         *
         * @param Preview HTMLNode
         * @param Entry HTMLNode
         * @returns {Promise}
         */
        hide: function (Preview, Entry) {
            if (!Entry || Entry.nodeName !== 'ARTICLE') {
                Entry = Preview.getParent('article')
            }

            Entry.removeClass('active');

            var animation = {
                opacity: 0
            };

            if (this.$left) {
                animation.left = this.$left - 15;
            } else {
                animation.right = this.$right - 15;
            }

            return new Promise(function (resolve) {
                moofx(Preview).animate(animation, {
                    duration: 250,
                    callback: function () {
                        Preview.setStyle('display', 'none');
                        Preview.set('data-qui-open', 0);

                        resolve();
                    }
                })
            })
        },

        /**
         * Show site preview
         *
         * @param Preview HTMLNode
         * @param Entry HTMLNode
         * @returns {Promise}
         */
        show: function (Preview, Entry) {
            Preview.setStyle('display', 'block');
            Preview.set('data-qui-open', 1);

            if (!Entry || Entry.nodeName !== 'ARTICLE') {
                Entry = Preview.getParent('article')
            }

            Entry.addClass('active');

            var animation = {
                opacity: 1
            };

            if (this.$left) {
                animation.left = this.$left;
            } else {
                animation.right = this.$right;
            }

            return new Promise(function (resolve) {
                moofx(Preview).animate(animation, {
                    duration: 250,
                    callback: resolve
                })
            })
        },

        /**
         * Mouse enter event
         *
         * @param event
         */
        mouseEnterEvent: function (event) {
            var Entry   = event.target,
                Preview = Entry.getElement('.qui-control-preview');

            if (!Entry) {
                return;
            }

            this.show(Preview, Entry);
        },

        /**
         * Mouse leave event
         *
         * @param event
         */
        mouseLeaveEvent: function (event) {
            var Entry   = event.target,
                Preview = Entry.getElement('.qui-control-preview');

            if (!Entry) {
                return;
            }

            this.hide(Preview, Entry);
        },

        /**
         * Calc sizes
         */
        calcSizes: function () {
            // mobile
            if (QUI.getWindowSize().x < 768) {
                this.calcSizesMobile();
                return;
            }

            if (!this.previews || this.previews.length < 1) {
                return;
            }

            this.windowWidth  = QUI.getWindowSize().x;
            this.controlWidth = this.getElm().getSize().x;
            this.controlPos   = this.getElm().getPosition().x; // left corner pos

            var self         = this,
                Preview      = this.previews[0],
                previewWidth = this.getAttribute('previewwidth').toInt();

            var previewPos = Preview.measure(function () {
                return this.getPosition().x;
            });

            // show preview on the left side
            if (this.getAttribute('opendirection') === 'left') {
                this.$right = this.controlWidth;
                this.$left  = null;

                // preview is wider than available space
                if (previewPos < 20 ||
                    20 + previewWidth > this.controlPos) {
                    this.$width = this.controlPos - 20;
                } else {
                    this.$width = previewWidth;
                }

            } else {
                // show preview on the right side
                this.$right = null;
                this.$left  = this.controlWidth;

//                console.warn("this.controlPos", this.controlPos)
//                console.log("previewPos", previewPos)
//                console.log("previewWidth", previewWidth)
//                console.log("controlWidth", this.controlWidth)
//                console.log("this.windowWidth", this.windowWidth)
//                console.log("this.$width", this.$width)

                // preview is wider than available space
                if (previewPos + previewWidth > this.windowWidth - 20) {
                    this.$width = this.windowWidth - previewPos - 20 ;
                } else {
                    this.$width = previewWidth;
                }

//                console.log("this.$width", this.$width)
            }

            this.previews.forEach(function (Preview) {
                // preview is open now
                if (Preview.get('data-qui-open') == 1) {
                    Preview.setStyles({
                        left    : self.$left,
                        right   : self.$right,
                        width   : self.$width,
                        position: null
                    });

                    return;
                }

                // preview ist closed
                Preview.setStyles({
                    left    : self.$left ? self.$left - 20 : self.left,
                    right   : self.$right ? self.$right - 20 : self.$right,
                    width   : self.$width,
                    position: null
                });
            });
        },

        /**
         * Calc sizes for mobile
         */
        calcSizesMobile: function () {
            this.previews.forEach(function (Preview) {
                Preview.setStyles({
                    left    : 0,
                    right   : 0,
                    width   : '100%',
                    position: 'relative'
                });
            });
        }
    });
});