/**
 *Baut das Tour-Panel auf
 *
 */
define('package/quiqqer/tour/bin/Tours', [
    'qui/QUI',
    'qui/controls/desktop/Panel',
    'controls/grid/Grid',
    'Ajax',
    'qui/controls/buttons/Button',
    'Locale'

], function (QUI, QUIPanel, Grid, Ajax, QUIButton, QUILocale) {
    "use strict";

    var lg = 'quiqqer/tour';

    return new Class({

        Extends: QUIPanel,
        Type: 'package/quiqqer/tour/bin/Tours',

        Binds: [
            '$onCreate',
            '$onResize',
            '$onInject',
            '$onClick',
            '$onDblClick',
            'refresh'
        ],

        options: {
            title: QUILocale.get(lg, 'tours.panel.title')
        },

        /**
         * event : initialize
         * @param options
         */
        initialize: function (options) {
            this.parent(options);

            this.$Grid = null;
            this.$Grid = null;

            this.addEvents({
                onCreate: this.$onCreate,
                onResize: this.$onResize,
                onInject: this.$onInject
            });
        },

        /**
         * event : on create
         */
        $onCreate: function () {

            // Buttons
            this.addButton(
                new QUIButton({
                    text: QUILocale.get(lg, 'play.button'),
                    name: 'Start Tour',
                    textimage: 'fa fa-play',
                    disabled: true,
                    events: {
                        onClick: function () {
                            var data = this.$Grid.getSelectedData()[0];

                            this.startTour(data['package'], data.id);
                        }.bind(this)
                    }
                })
            );
            this.addButton(
                new QUIButton({
                    text: QUILocale.get(lg, 'help.button'),
                    name: 'Start Help',
                    textimage: 'fa fa-question',
                    disabled: false,
                    events: {
                        onClick: function () {
                            QUI.Storage.set('ShowTourQuestionMark', 1);
                            require(['package/quiqqer/tour/load'], function(loadFunction){
                                loadFunction();
                            });
                        }.bind(this)
                    }
                })
            );


            // Grid
            var Container = new Element('div').inject(
                this.getContent()
            );

            this.$Grid = new Grid(Container, {
                pagination: true,
                serverSort: false,
                columnModel: [{
                    header: QUILocale.get(lg, 'panel.title'),
                    dataIndex: 'title',
                    dataType: 'string',
                    width: 150
                }, {
                    header: QUILocale.get(lg, 'panel.description'),
                    dataIndex: 'description',
                    dataType: 'string',
                    width: 450
                }, {
                    header: QUILocale.get(lg, 'panel.package'),
                    dataIndex: 'package',
                    dataType: 'string',
                    width: 150
                 }
                ]
            });

            this.$Grid.addEvents({
                onRefresh: this.refresh,
                onDblClick: this.$onDblClick,
                onClick: this.$onClick
            });

            this.$Message = new Element('span', {
                id: 'tours-message',
                html: QUILocale.get('quiqqer/tour', 'error.noToursFound'),
                styles: {
                    display: 'none'
                }
            }).inject(Container.parentElement);
        },

        /**
         * event : on resize
         */
        $onResize: function () {
            if (!this.$Grid) {
                return;
            }

            var Body = this.getContent();

            if (!Body) {
                return;
            }

            var size = Body.getSize();

            this.$Grid.setHeight(size.y - 40);
            this.$Grid.setWidth(size.x - 40);
        },


        /**
         * event: single click
         */
        $onClick: function () {
            var startTourButton = this.getButtons('Start Tour'),
                selected        = this.$Grid.getSelectedIndices().length;

            if (selected) {
                startTourButton.enable();
            } else {
                startTourButton.disable();
            }
        },

        /**
         * event : dbl click
         */
        $onDblClick: function () {
            var data = this.$Grid.getSelectedData()[0];

            this.startTour(data['package'], data.id);
        },

        /**
         *event : on Inject
         */
        $onInject: function () {
            this.refresh();
        },

        /**
         * Refresh the complete list
         */
        refresh: function () {
            this.Loader.show();

            Ajax.get('package_quiqqer_tour_ajax_getListForGrid', function (result) {

                if (result.length > 0) {
                    this.$Grid.container.style.display = 'block';
                    this.$Grid.setData({
                        data: result
                    });    
                } else {
                    this.$Grid.container.style.display = 'none';
                    this.$Message.style.display = 'block';
                }

                this.Loader.hide();

            }.bind(this), {
                'package': 'quiqqer/tour'
            });
        },

        /**
         * Return the tour data
         *
         * @param {String} pkg
         * @param {String} index
         * @returns {Promise}
         */
        getTour: function (pkg, index) {
            return new Promise(function (resolve) {
                Ajax.get('package_quiqqer_tour_ajax_getTour', resolve, {
                    'package': 'quiqqer/tour',
                    pkg: pkg,
                    'index': index
                })
            });
        },

        /**
         * Start a tour
         *
         * @param {String} pkg
         * @param {String} index
         */
        startTour: function (pkg, index) {
            this.getTour(pkg, index).then(function (TourData) {
                    if (typeof TourData === 'undefined') {
                        return;
                    }

                    if (typeOf(TourData) !== 'object') {
                        return;
                    }

                    if ("require" in TourData) {
                        require([TourData.require], function (Tour) {
                            Tour.reset();
                            Tour.start();
                        });
                        return;
                    }

                    require(['package/quiqqer/tour/bin/classes/Tour'], function (Tour) {
                        var i, len, title, options, description, attachTo, advanceOn;

                        var Current = new Tour(),
                            steps = TourData.steps || [];

                        for (i = 0, len = steps.length; i < len; i++) {
                            title = '';
                            description = '';
                            attachTo = '';
                            advanceOn = '';

                            if (typeOf(steps[i].title) == 'array') {
                                title = QUILocale.get(steps[i].title[0], steps[i].title[1]);
                            } else {
                                title = steps[i].title
                            }

                            if (typeOf(steps[i].description) == 'array') {
                                description = QUILocale.get(steps[i].description[0], steps[i].description[1]);
                            } else {
                                description = steps[i].description
                            }

                            options = {
                                title: title,
                                text: description
                            };

                            Current.addStep(
                                TourData.package + i,
                                options
                            );
                        }

                        Current.start();
                    });
                }
            );
        }
    });
});