/**
 * Created by jhwang on 14-6-21.
 */
define(function (require, exports) {
    //require('fabric');
    var G = require('./idgen');
    var WdtType = require('./widgettype');
    var Path = require('./path');
    var Ctx = require('./appcontext').AppContext;

    function Slide() {
        // 画布对象信息,fabric序列化反序列化对象
        this._canvasInfo = null;
        // 关联属性对象
        this._relationInfo = [];
        // 动画描述对象
        this._animationInfo = [];

        //分辨率
        this._presentfmt = "1280:800";


        //fabric canvas 对象
        this._canvas = null;

        // 是否是编辑器状态
        this._isEditMode = true;

        // id 产生器
        this._WIdGen = new G.Widget();
        this._TIdGen = new G.TimeNode();
        this._RIdGen = new G.Relation();
    };

    Slide.prototype.dispose = function () {
        if (this._canvas) {
            this._canvas.clear();
            this._canvas.dispose();
            this._canvas = null;
        } else {
            console.log('--no fabric canvas to dispose');
        }

        this._canvasInfo = null;
        this._relationInfo = null;
        this._animationInfo = null;
        this._WIdGen = null;
        this._TIdGen = null;
        this._RIdGen = null;
    };

    Slide.prototype.addRelationInfo = function (info) {
        if (!info.id) info.id = this._RIdGen.newId();
        this._relationInfo.push(info);
        return info.id
    }
    Slide.prototype.delRelationInfo = function (id) {
        for (var i = 0; i < this._relationInfo.length; i++) {
            if (this._relationInfo[i].id === id) {
                this._relationInfo.splice(i, 1);
            }
        }
    }

    Slide.prototype.getRelationInfo = function (id) {
        for (var i = 0; i < this._relationInfo.length; i++) {
            if (this._relationInfo[i].id === id) {
                return this._relationInfo[i];
            }
        }
    }

    Slide.prototype.addAnimationInfo = function (info) {
        this.delAnimationInfo(info.id);
        this._animationInfo.push(info);
    }

    Slide.prototype.delAnimationInfo = function (id) {
        for (var i = 0; i < this._animationInfo.length; i++) {
            if (this._animationInfo[i].id === id) {
                this._animationInfo.splice(i, 1);
            }
        }
    }

    Slide.prototype.getAnimationInfo = function (id) {
        for (var i = 0; i < this._animationInfo.length; i++) {
            if (this._animationInfo[i].id === id) {
                return this._animationInfo[i];
            }
        }
        return null;
    }

    Slide.prototype.NewRId = function () {
        return this._RIdGen.newId();
    }

    Slide.prototype.NewWId = function (wtype) {
        return this._WIdGen.newId(wtype);
    }
    Slide.prototype.LoadId = function (id) {
        G.SlideIdGen.loadId(id);
    }
    Slide.prototype.NewTId = function (wtpe) {
        return this._TIdGen.newId();
    }
    /**
     * 设置分辨率
     * @param _str
     */
    Slide.prototype.setFmt = function (_str) {
        this._presentfmt = _str;
    }
    /**
     * 初始化
     * @param canvas
     */
    Slide.prototype.init = function (canvas, isEditMode) {
        var def = $.Deferred();
        var _self = this;

        _self._canvas = canvas;
        _self._canvas.backgroundColor = 'white';
        _self._isEditMode = isEditMode;
        if (_self._isEditMode) {
            //编辑模式下
            seajs.use('./editor/assert/js/slide_edit.js', function () {
                _self._initEditingMode(function () {
                    def.resolve();
                });

            });
        } else {
            //播放模式下处理方式
            seajs.use('./player/assert/js/slide_play.js', function () {
                _self._initPlayingMode().done(function () {
                    def.resolve();
                });
            });
        }
        return def.promise();
    };


    Slide.prototype.getCanvasSize = function () {
        return [this._canvas.width, this._canvas.height];
    }

    /**
     * 返回当前slide的物理位置
     * @returns {string}
     */
    Slide.prototype.getCurSlidePath = function () {
        return  Path.join(Ctx.getCurSlidePackPath(), "/slides/", this.Name);
    };

    /**
     * 返回当前Thumb的物理位置
     * @returns {string}
     */
    Slide.prototype.getCurThumbPath = function () {
        return  Path.join(this.getCurSlidePath(), 'thumb.jpg');
    };

    Slide.prototype.getCurJsonPath = function () {
        return  Path.join(this.getCurSlidePath(), 'slide.json');
    }
    Slide.prototype.getCurMediaPath = function () {
        return  Path.join(this.getCurSlidePath(), "/media");
    };
    /**
     * slide序列化
     * @returns {json}
     */
    Slide.prototype.toJSON = function () {
        var obj = {"canvas": this._canvas, "rels": this._relationInfo, "animationInfo": this._animationInfo, "presentfmt": this._presentfmt };
        var obj = this._shortPath(obj);
        return JSON.stringify(obj);
    };

    Slide.prototype.getRelativePath = function (src) {
        return Path.trimPosix(decodeURI(src).replace(this.getCurSlidePath(), ''));
    };

    /**
     * 将图片路径转换为相对路径
     * @private
     */
    Slide.prototype._shortPath = function (obj) {
        var _self = this;


        var tmp = JSON.parse(JSON.stringify(obj));
        $.each(tmp.canvas.objects, function () {
            this.src = decodeURI(this.src);
            if (this.src) {
                //this.src = Path.trimPosix(this.src.replace(_self.getCurSlidePath(), ''));
                this.src = Path.trimPosix(this.src.replace(/.*?sco\//ig, ''));
                //去随机数
                //this.src = this.src.replace(/(.+?)\?(\d.+\d\b)/g, "$1");
                this.src = this.src.replace(/(.+?)\?(.*)/g, "$1");
                if (this.src.indexOf(Global.CurrentSlide.c.getCurSlidePath()) >= 0) {
                    this.src = this.src.replace(Global.CurrentSlide.c.getCurSlidePath(), '');
                }
            }
        });
        $.each(tmp.rels, function () {
            this.src = decodeURI(this.src);
            if (this.src) {

                this.src = _self.getRelativePath(this.src);
            }
        });
        if (tmp.canvas.backgroundImage) {
            tmp.canvas.backgroundImage.src = _self.getRelativePath(tmp.canvas.backgroundImage.src);
        }
        if (tmp.canvas.background && tmp.canvas.background.source) {
            tmp.canvas.background.source = _self.getRelativePath(tmp.canvas.background.source);
        }
        return tmp;
    };
    /**
     * 还原相对路径为真实路径
     * @param obj
     * @private
     */
    Slide.prototype._fullPath = function (obj) {
        var _self = this;
        $.each(obj.canvas.objects, function () {
            if (this.src) {
                if (this.src.split('.').length <= 1 || this.type === WdtType.T) {
                    this.src = this.src + '?' + Math.random();
                } else {
                    this.src = Path.join(_self.getCurSlidePath(), this.src) + '?' + Math.random();
                }
            }
        });

        $.each(obj.rels, function () {
            if (this.src) {
                if (this.type == 'dir') {
                    this.src = this.src
                } else {
                    this.src = Path.join(_self.getCurSlidePath(), this.src);
                }

            }
        });

        if (obj.canvas.backgroundImage) {
            obj.canvas.backgroundImage.src = Path.join(_self.getCurSlidePath(), obj.canvas.backgroundImage.src);
        }
        if (obj.canvas.background && obj.canvas.background.source) {
            obj.canvas.background.source = Path.join(_self.getCurSlidePath(), obj.canvas.background.source);
        }
    };

    Slide.prototype.loadFromJSON = function (json, completeCallback) {
        var _self = this;
        if (!json) return;
        // serialize if it wasn't already
        var serialized = (typeof json === 'string')
            ? JSON.parse(json.replace(/\r\n/g, "").replace(/\n/g, '\\n'))
            : json;

        //在播放状态下，将widget对象隐藏，不在后面的canvas上显示
        if (this._isEditMode === false) {
            var canvasObjs = serialized.canvas.objects;
            for (var i = 0; i < canvasObjs.length; i++) {
                if (WdtType.isComplexWidget(canvasObjs[i].type)) {
                    canvasObjs[i].visible = false;
                }
            }
        }

        _self._relationInfo = serialized.rels || [];
        _self._animationInfo = serialized.animationInfo || [];
        _self._canvasInfo = serialized.canvas.objects || [];

        // 此处进一步处理反序列化过来的对象（新建页由于是营造的假数据，所以不需要拼接全路径）
        if (Ctx.isCurNewBlankSlide) {
            //如果当前页是新建页，则load之后需要将ctx里的标记值设置回来，防止影响后面正常页面加载
            Ctx.isCurNewBlankSlide = false;
        } else {
            _self._fullPath(serialized);
        }

        //console.log(serialized.canvas);

        _self._canvas.loadFromJSON(serialized.canvas, function () {

            _self._fillRelInfo();
            _self._pushId();
            if (completeCallback) {
                completeCallback();
            }
        });

    };
    /**
     * 设置背景
     * @param src
     */
    Slide.prototype.setBackgroundImage = function (src, repeat) {
        var _that = this;
        if (repeat) {
            this._canvas.backgroundImage = null;
            this._canvas.backgroundColor = new fabric.Pattern({
                source: src,
                repeat: repeat,
                offsetx: 0,
                offsety: 0
            });

        } else {
            this._canvas.backgroundColor = null;
            this._canvas.setBackgroundImage(src, this._canvas.renderAll.bind(this._canvas), {width: this._canvas.width, height: this._canvas.height});
        }
        var sid = setTimeout(function () {
            _that._canvas.renderAll();
            clearTimeout(sid);
        }, 150)
    }
    /**
     * 根据反序列化的json，初始化slide的基本信息，例如canvasObjects和widgets
     * @private
     */
    Slide.prototype._initSlideInfo = function () {

    }

    Slide.prototype._fillRelInfo = function () {
        var _self = this;
        $.each(_self._canvas.getObjects(), function () {
            //初始化 relation 信息
            for (var i = 0, len = _self._relationInfo.length; i < len; ++i) {
                if (_self._relationInfo[i].id === this.rid) {
                    //console.log("this is---",this);
                    this.setRelInfo(_self._relationInfo[i]);
                }

            }

        });
    };

//把 id 添加到id generator 池中
    Slide.prototype._pushId = function () {
        var _self = this;
        $.each(_self._canvasInfo, function () {
            _self._WIdGen.loadId(this.type, this.id);
        });

        $.each(_self._relationInfo, function () {
            _self._RIdGen.loadId(this.id);
        });

        $.each(_self._animationInfo, function () {
            _self._TIdGen.loadId(this.id);
        });
    };

    /**
     * 向画布添加一个对像
     * @param fabricObj
     * @returns {Slide}
     */
    Slide.prototype.add = function (fabricObj, property) {
        var _self = this;
        if (!fabricObj.id)
            fabricObj.id = _self._WIdGen.newId(fabricObj.type);
        if (property) {
            for (var i in property) {
                fabricObj[i] = property[i];
            }
        }
        if (WdtType.isComplexWidget(fabricObj.type) && fabricObj.type != 'Spot') {
            fabricObj.setStroke('#d0cece');
            fabricObj.strokeWidth = 1;
            fabricObj.setShadow('0px 0px 5px rgba(0,0,0,0.4)');
        }
        _self._canvas.add(fabricObj);
        EventBase.fireEvent('addElment',true);
        return _self;
    };

    /**
     * 通过json为canvas添加一个对象
     * @param JSON  string array
     * @param callback
     */
    Slide.prototype.addFromJSON= function(_arr,callback)
    {
        var _canvasJson = JSON.parse(this.toJSON());
        var _objectJson = _arr;
        for(var i=0;i<_objectJson.length;i++)
        {
            _canvasJson.canvas.objects.push(_objectJson[i]);
            if(_objectJson[i]['rinfo'] )
            {
                _canvasJson.rels.push(_objectJson[i]['rinfo']);
            }
        }
        return _canvasJson;
    }
    /***
     * 重绘画布
     * @returns {Slide}
     */
    Slide.prototype.renderAll = function () {
        var _self = this;
        _self._canvas.renderAll();
        return _self;
    };

    /**
     * 清空画布
     * @returns {Slide}
     */
    Slide.prototype.clear = function () {
        var _self = this;
        _self._canvas.clear();
        _self._canvas.dispose();
        return _self;
    };
    /**
     * 删除当前选中对象或群组
     */
    Slide.prototype.removeObject = function () {
        var a = this._canvas.getActiveGroup(), d = this._canvas.getActiveObject();
        a && a.remove.apply(this._canvas, a._objects);
        //a && a.remove.apply(a,a.objects);
        d && d.remove();
        this._canvas.deactivateAll();
        this.renderAll();
    }
    /**
     * 创建一个空的画布 HTMLElement     编辑时用
     * @param _tar  目标位置
     * @param pageid    绑定ID
     * @returns {*|jQuery|HTMLElement}
     */
    Slide.prototype.createStage = function (_tar, pageid, callback) {

        //this._canvas && this._canvas.dispose();
        var _p = null;
//        $('#stage_m_l').css('width', DEFAULT_STAGE.left);
//        $('#stage_m_r').css('width', DEFAULT_STAGE.left - 18);
        if(this._canvas)
        {
            this._canvas.clear();
            this._canvas.dispose();
            _tar.append(this._canvas.wrapperEl.parentNode);
            this._canvas._initEventListeners();
            this.start().done(function(){
                callback && callback();
            });

        }else
        {
            var css = {"background-color": "#ffffff",
                "-webkit-box-shadow": "0px 0px 4px #000",
                "border": "1px solid #000",
                "margin": "0 auto",
                "width": DEFAULT_STAGE.width + "px",
                "height": DEFAULT_STAGE.height + "px"
            };
            _p = $('<div id="stage_m_c" style="box-shadow: 2px 2px 10px 5px rgba(100,100,100,0.3);position:relative;-webkit-transform-origin: 0 0; display: inline-block;width: ' + DEFAULT_STAGE.width + 'px;height: ' + DEFAULT_STAGE.height + 'px;">' +
                '<canvas width="' + DEFAULT_STAGE.width + '" height="' + DEFAULT_STAGE.height + '" id="' + (pageid + "_stage") + '"></canvas></div>');
            if(DEFAULT_STAGE.scale) _p.css('-webkit-transform','scale('+DEFAULT_STAGE.scale+')');
            if(DEFAULT_STAGE.left) _p.css('left',DEFAULT_STAGE.left);
            if(DEFAULT_STAGE.top) _p.css('top',DEFAULT_STAGE.top);

            _tar.append(_p);
            this.init(new fabric.Canvas(pageid + "_stage"), true).done(function () {
//            console.log('_______________________slide')
                callback && callback();
            });
        }

        //var _stage = $('.canvas-container');
        //_stage && _stage.css('-webkit-transform','scale('+DEFAULT_STAGE.scale+')');
    };
    exports.Slide = Slide;
})
;