/**
 * slide播放模块
 * Date: 2014/06/23
 * Author: luxing@iflytek.com
 * @version 1.0
 * @module player
 */
define(function (require, exports) {
        var Slide = require('../../../share/assert/js/slide').Slide;
        var WdtType = require('../../../share/assert/js/widgettype');
        var path = require('../../../share/assert/js/path');
        var ctx = require('../../../share/assert/js/appcontext').AppContext;
        var IOUtil;
        if (RunningPlatform === ctx.RunningPlatform.NodeWebkit) {
            IOUtil = require("../../../share/assert/js/ioutil_desktop.js").IOUtil
        }
        else if (RunningPlatform === "Android") {
            IOUtil = require("../../../share/assert/js/ioutil_android.js").IOUtil;
        }
        else if (RunningPlatform === "CEF") {
            IOUtil = require("../../../share/assert/js/ioutil_cef.js").IOUtil;
        }
        else {
            IOUtil = require("../../../share/assert/js/ioutil_web.js").IOUtil;
        }

        /**
         * 初始化播放
         * @private
         */
        Slide.prototype._initPlayingMode = function () {
            var def = $.Deferred();
            var _self = this;
            //反序列化json
            var jsonPath = _self.getCurSlidePath() + "/slide.json";
            jsonPath = path.trimPosix(jsonPath);

            //IOUtil.readFile(jsonPath).done(function (jsonStr) {
                _self.loadFromJSON(_self._canvasJson, function () {
                    //静态化页面对象
                    var objs = _self._canvas.getObjects();
                    var animateObjs = [];
                    for (var i = 0; i < objs.length; i++) {
                        if (objs[i].type === "TextField") {
                            objs[i].editable = false;
                            animateObjs.push(objs[i]);
                        }
                        if (objs[i].type === "Img" || objs[i].type === "Graphica") {
                            animateObjs.push(objs[i]);
                        }
                        objs[i].hasBorders = false;
                        objs[i].hasControls = false;
                        objs[i].selectable = false;
                    }
                    _self.renderAll();
                    $(".canvas-container").width("100%");
                    $(".canvas-container").height("100%");
                    _self.bindAnimations(animateObjs);
                   /* _self.loadWidgets().done(function () {
                        def.resolve();
                    });*/
                    def.resolve();
                });
            //});
            return def.promise();
        };

        /**
         * 加载widgets(复杂类型)
         */
        Slide.prototype.loadWidgets = function () {

            var def = $.Deferred();
            var _self = this;
            if(this.widgetIsShow){
                def.resolve();
                return;
            }
            this.widgetIsShow = true;
            var canvasObjs = _self._canvas.getObjects();
            var widgetObjs = [];
            for (var i = 0; i < canvasObjs.length; i++) {
                //先把widget对象过滤出来
                if (WdtType.isComplexWidget(canvasObjs[i].type)) {
                    widgetObjs.push(canvasObjs[i]);
                }
            }
            for (var i = 0; i < widgetObjs.length; i++) {
                //拿到relationID，然后找到对应的资源包
                var relationID = widgetObjs[i].rid;
                var relatedResPath = path.join(_self.getCurSlidePath(), _self.findRelatedRes(relationID).src);
                if (ctx.isSingleWidgetPlayMode) {
                    relatedResPath = ctx.singleWidgetPath;
                }
                $(document).queue('showWidgets', _self._createShowWidgetTask(widgetObjs[i], relatedResPath));
            }

            $(document).queue('showWidgets', function () {
                console.log("load widgets all done");
                def.resolve();
            });

            $(document).dequeue('showWidgets');

            return def.promise();
        }

        /**
         * 根据relationID获取资源描述对象
         * @param relationID
         * @returns {object}
         */
        Slide.prototype.findRelatedRes = function (relationID) {
            var relationInfo = this._relationInfo;
            for (var i = 0; i < relationInfo.length; i++) {
                if (relationInfo[i].id === relationID) {
                    return relationInfo[i];
                }
            }
        }

        Slide.prototype.clearWidget = function(){
            var _self = this;
            for(var i=0;i<_self.widgetArray.length;i++)
            {
                _self.widgetArray[i].remove();
            }
            _self.widgetArray = [];
            _self.widgetIsShow = false;
        }
        /**
         * 将wiget展示在指定区域
         * @param {object} widgetObj对象描述信息
         * @param {string} widget对应资源路径
         * @param {function} 队列要执行的下一个函数
         */
        Slide.prototype.showWidget = function (widgetObj, relatedResPath, next) {
            var _self = this;
            //每个wiget外面都有个container，用来指定位置
            var widgetId = "widget_" + widgetObj.id;
            var widgetLeft = widgetObj.left;//+(GlobalStage._slideWidth*GlobalStage._curSlidePageIndex);
            var widgetTop = widgetObj.top;
            var widgetWidth = widgetObj.width;
            var widgetHeight = widgetObj.height;

            //获取wigetDomDiv，并设定缩放比例
            var parentContainerId = _self.parentContainerId;
//            var wigetDomDiv = $('<div><div class="loader"></div></div>');
           widgetObj.getRenderDOM(relatedResPath).done(function (wigetDomDiv) {
                wigetDomDiv = $(wigetDomDiv);
                wigetDomDiv.attr("domType", "widgetDiv");
                wigetDomDiv.attr("id", widgetId);
                var ctxZoomX = ctx.zoomRate.x;
                var ctxZoomY = ctx.zoomRate.y;
                widgetLeft = widgetLeft * ctx.zoomRate.x;
                widgetTop = widgetTop * ctx.zoomRate.y;
                if (ctx.isSingleWidgetPlayMode) {
                    widgetLeft = (1000 - widgetWidth) / 2;
                    widgetTop = (620 - widgetHeight) / 2;
                }
                wigetDomDiv.css({position: "absolute", left: widgetLeft, top: widgetTop, width: widgetWidth, height: widgetHeight});
                var zoomX = ctxZoomX * widgetObj.scaleX;
                var zoomY = ctxZoomY * widgetObj.scaleY;

                if (wigetDomDiv.attr("videoType") === "flash" || wigetDomDiv.find("video")[0]) {
                    widgetWidth = parseInt(widgetWidth * zoomX);
                    widgetHeight = parseInt(widgetHeight * zoomY);
                    wigetDomDiv.width(widgetWidth);
                    wigetDomDiv.height(widgetHeight);
                } else {
                    //使用transform等比例缩放
                    var translateX = -widgetWidth * (1 - zoomX) / 2;
                    var translateY = -widgetHeight * (1 - zoomY) / 2;
                    if (widgetObj.type === WdtType.Types.CnEval || widgetObj.type === WdtType.Types.EnEval || widgetObj.type === WdtType.Types.Situdlg) {
                        if (zoomX < 1 || zoomY < 1) {
                            zoomX = 1;
                            zoomY = 1;
                        }
                    }
                    var _pageTransformCSS = {
                        'transform': 'matrix(' + zoomX + ',0,0,' + zoomY + ',' + translateX + ' ,' + translateY + ')',
                        '-moz-transform': 'matrix(' + zoomX + ',0,0,' + zoomY + ',' + translateX + ' ,' + translateY + ')',
                        '-webkit-transform': 'matrix(' + zoomX + ',0,0,' + zoomY + ',' + translateX + ' ,' + translateY + ')'
                    };
                    wigetDomDiv.css(_pageTransformCSS);
                }


                if (wigetDomDiv.attr("videoType") === "flash" && RunningPlatform === ctx.RunningPlatform.NodeWebkit) {

                    wigetDomDiv.find("embed").hide();
                }
                _self.widgetArray.push(wigetDomDiv);
//                $("#" + parentContainerId).append(wigetDomDiv);
                _self._container.append(wigetDomDiv);

                next();
            });
        }


        Slide.prototype._createShowWidgetTask = function (widgetObj, relatedResPath) {
            var _self = this;
            return function (next) {
                _self.showWidget(widgetObj, relatedResPath, next);
            }
        }

        Slide.prototype.bindAnimations = function (animateObjs) {
            var _self = this;
            for (var i = 0; i < animateObjs.length; i++) {
                (function () {
                    var objId = animateObjs[i].id;
                    var animationInfo = _self.getAnimationInfo(objId);
                    if (animationInfo) {
                        var trigger = animationInfo.trigger;
                        var tempAniObj = animateObjs[i];
                        _self._initAnimation(tempAniObj, animationInfo);
                        tempAniObj.on(trigger, function () {
                            _self._startAnimate(animationInfo)
                        });
                    }
                })();
            }
        }

        Slide.prototype._startAnimate = function (animationInfo) {
            var _self = this;
            if (animationInfo) {
                var objId = animationInfo.id;
                var attr = animationInfo.attr;
                var endValue = animationInfo.end;
                var duration = animationInfo.duration;
                _self._getObjectById(objId).animate(attr, endValue, {
                    onChange: _self._canvas.renderAll.bind(_self._canvas),
                    duration: duration
                });
            }
        }

        Slide.prototype._getObjectById = function (objId) {
            var _self = this;
            var objs = _self._canvas.getObjects();
            for (var i = 0; i < objs.length; i++) {
                if (objs[i].id === objId) {
                    return objs[i];
                }
            }
            return null;
        }

        Slide.prototype._initAnimation = function (animateObj, animationInfo) {
            var _self = this;
            if (animationInfo && animationInfo.type === "fadeIn") {
                var startValue = animationInfo.start;
                animateObj.opacity = 0;
                _self.renderAll();
            }
        }
        Slide.prototype.loadWhiteBord = function(_uri){
            var _self = this;
            var _img = new Image()
                _img.src = _uri;
            _self.setBackgroundImage(_uri);
            _self.penData = false;
        }
        exports.SlidePlay = Slide;
    }
);