/**
 * H5 Offline DP
 *
 * read http://192.168.1.185/wiki/index.php/Livestreaming:V3_flashData
 *
 * Created by shanglt on 2017/1/6.
 */
!(function(window, document) {

    console.log('liveModule v.0.1.1');

    /**
     * 获取16进制RGB颜色
     *
     * */
    function getHexRGB(o) {
        var h = parseInt(o, 10).toString(16).toUpperCase();
        var hl = h.length;
        for (var i = 0; i < 6 - hl; i++) {
            h = '0' + h;
        }

        return '#' + h;
    }

    function dpCenter() {
        var t = $('#drawPanel').parent().height() - $('#drawPanel').height();
        if (t < 0) {
            t = 0;
        }

        $('#drawPanel').css('margin-top', t / 2);
    }

    /**
     * 如果参数为string，转换为json
     *
     * */
    function toJson(j) {
        if (typeof j === "string") {
            j = JSON.parse(j);
        }
        return j;
    }

    /**
     * 判断翻页是白板
     *
     * */
    function isWhiteBorad(j) {
        return j.url === '#' && j.fileName === 'WhiteBorad';
    }

    /**
     * 获取离线图片地址
     * */
    function getOfflineImagePath(imageRootPath, j) {
        return imageRootPath + '/image/' + j.docid + '/' + j.page + '.jpg';
    }

    /**
     * 画板类
     *
     * */
    var DrawPanel = function(id, imageRootPath) {
        if (!id) {
            id = 'drawPanel';
        }

        this.id = id;
        this.imageRootPath = imageRootPath;

        var canvas = document.getElementById(this.id);
        if (!canvas) {
            throw new Error('canvas is not exist');
        }

        this.caches = {};
        this.currentDocKey = {};
    };

    /**
     * type
     * 0:清屏
     * 1:清除上一步
     * 2:绘线
     * 3:矩形
     * 4:圆形
     * 5:文字
     * 6:删除整个文档
     * 7:清理文档每一页的画笔数据
     * 8:删除所有文档，以及所有文档的画笔数据
     * 9:清除指定ID的画笔数据
     * */
    var DRAW_TYPE = {
        CLEAR_SCREEN: 0, // 清屏
        CLEAR_PREV: 1, // 清除上一步
        DRAW_LINE: 2, // 绘线
        DRAW_RECT: 3, // 矩形
        DRAW_ARC: 4, // 圆形
        DRAW_TXT: 5, // 文字
        DELETE_DOC: 6, // 删除整个文档
        CLEAR_DOC_DRAWS: 7, // 清理文档每一页的画笔数据
        DELETE_WHOLE_DOC_AND_DRAW: 8, // 删除所有文档，以及所有文档的画笔数据
        DELETE_DRAW_BY_ID: 9 // 清除指定ID的画笔数据
    };


    DrawPanel.prototype = {

        /**
         * 清空缓存
         * */
        clearCache: function() {
            this.caches = {};
            this.clearRect();
        },

        /**
         * 重新绘制
         * */
        reflip: function() {
            var dp = this;
            var c = dp.caches[dp.currentDocKey];
            if (c && c.j) {
                dp.flip(c.j);
            }
        },

        /**
         * 画板翻页
         *
         * */
        flip: function(j) {
            if (!j) {
                return;
            }

            if ($('#drawPanel').is(":hidden")) {
                $('#noppt').hide();
                $('#drawPanel').show();
            }

            j = toJson(j);

            var dp = this;

            var k = j.docid + '_' + j.page;

            dp.currentDocKey = k;

            if (!dp.caches[k]) {
                dp.caches[k] = {
                    doc: {
                        id: j.docid,
                        num: j.page,
                        url: j.url,
                        isWhiteBorad: isWhiteBorad(j)
                    },

                    j: j,

                    draws: []
                };
            }

            var canvas = document.getElementById(dp.id);
            var context = canvas.getContext('2d');

            // 白板
            if (isWhiteBorad(j)) {
                context.clearRect(0, 0, canvas.width, canvas.height);

                // 白板首次绘画需要更新高度
                dp.caches[k].needUpdatedHeight = true;

                $.each(dp.caches[k].draws, function(index, draw) {
                    dp.draw(draw, true);
                });
            } else {
                var image = new Image();
                image.src = getOfflineImagePath(dp.imageRootPath, j);

                image.onload = function() {
                    var imgHeight = this.height;
                    var imgWidth = this.width;

                    canvas.height = canvas.width * imgHeight / imgWidth;
                    dpCenter();

                    // if (window.devicePixelRatio) {
                    //     context.canvas.style.width = canvas.width + "px";
                    //     context.canvas.style.height = canvas.height + "px";
                    //     context.canvas.height = canvas.height * window.devicePixelRatio;
                    //     context.canvas.width = canvas.width * window.devicePixelRatio;
                    //     context.scale(window.devicePixelRatio, window.devicePixelRatio);
                    // }

                    context.drawImage(image, 0, 0, canvas.width, canvas.height);

                    $.each(dp.caches[k].draws, function(index, draw) {
                        dp.draw(draw, true);
                    });
                };
            }
        },

        /**
         * 清空画板数据
         * */
        clearRect: function() {
            var dp = this;
            var canvas = document.getElementById(dp.id);
            var context = canvas.getContext('2d');
            context.clearRect(0, 0, canvas.width, canvas.height);
        },

        /**
         * 清理文档每一页的画笔数据，清楚画笔数据
         * */
        clearDocDraws: function(data) {
            $.each(this.caches, function(k, v) {
                v.draws = [];
            });
        },

        /**
         * 清空屏幕，清空画图数据
         * */
        clearScreen: function(data) {
            var dp = this;
            dp.clearRect();

            var k = data.docid + '_' + data.page;
            dp.caches[k].draws = [];

            dp.flip(dp.caches[k].j);
        },

        /**
         * 清空上一步，删除上一步的画笔数据
         * */
        clearPrev: function(data) {
            var dp = this;
            dp.clearRect();

            var k = data.docid + '_' + data.page;

            dp.caches[k].draws.pop();
            dp.caches[k].draws.pop();

            dp.flip(dp.caches[k].j);

        },

        /**
         * 删除整个文档 TODO
         * */
        deleteDoc: function(data) {
            var dp = this;
            dp.clearRect();
        },

        /**
         * 删除所有文档，以及所有文档的画笔数据
         *
         * */
        deleteWholeDocAndDraw: function(data) {
            this.deleteWholeDocAndDrawData(data)
            this.resetDrawCurrentPage()
        },
        deleteWholeDocAndDrawData: function(data) {
            this.caches = {}
        },

        /**
         * 清除指定ID的画笔数据
         *
         * */
        deleteDrawById: function(data) {
            var dp = this;
            var k = data.docid + '_' + data.page;

            var drawid = data.drawid;
            var draw_data = dp.caches[k].draws;
            for (var i = draw_data.length - 2; i >= 0; i--) {
                if (draw_data[i].drawid === drawid) {
                    dp.caches[k].draws.splice(i, 1);
                }
            }
            dp.resetDrawCurrentPage();
        },

        /**
         * 重新绘制当前页画笔
         * */
        resetDrawCurrentPage: function() {
            var dp = this
            dp.clearRect()
            dp.reflip()
        },
        /**
         * 绘线
         *  */
        drawLine: function(data) {
            var dp = this;
            var canvas = document.getElementById(dp.id);
            var context = canvas.getContext('2d');

            var x0 = data.draw[0].x * canvas.width;
            var y0 = data.draw[0].y * canvas.height;

            context.beginPath();

            context.strokeStyle = getHexRGB(data.color);
            context.lineWidth = data.thickness * canvas.width / data.width;
            context.lineJoin = "round";

            // 起点
            context.moveTo(x0, y0);

            for (var i = 0; i < data.draw.length; i++) {
                var xn = data.draw[i].x * canvas.width;
                var yn = data.draw[i].y * canvas.height;

                context.lineTo(xn, yn);
            }

            context.stroke();
        },

        /**
         * 矩形
         * */
        drawRect: function(data) {
            var dp = this;
            var canvas = document.getElementById(dp.id);
            var context = canvas.getContext('2d');

            var x = data.draw.x * canvas.width;
            var y = data.draw.y * canvas.height;

            var w = data.draw.width * canvas.width;
            var h = data.draw.height * canvas.height;

            context.beginPath();
            context.strokeStyle = getHexRGB(data.color);
            context.lineWidth = data.thickness * canvas.width / data.width;
            context.lineJoin = "round";

            context.strokeRect(x, y, w, h);
            context.stroke();
        },

        /**
         * 圆形
         *
         * */
        drawArc: function(data) {
            var dp = this;
            var canvas = document.getElementById(dp.id);
            var context = canvas.getContext('2d');

            var r = data.draw.heightRadius * canvas.height;
            var x = data.draw.x * canvas.width - r;
            var y = data.draw.y * canvas.height - r;

            context.beginPath();
            context.strokeStyle = getHexRGB(data.color);
            context.lineWidth = data.thickness * canvas.width / data.width;
            context.lineJoin = "round";

            context.arc(x, y, r, 0, Math.PI * 2, true);

            context.stroke();
        },

        /**
         * 文字
         *
         * */
        drawTxt: function(data) {
            var dp = this;
            var canvas = document.getElementById(dp.id);
            var context = canvas.getContext('2d');
            var currentDrawDatas = dp.caches[dp.currentDocKey].draws
            if (currentDrawDatas[currentDrawDatas.length - 1].isNeedRedraw) {
                currentDrawDatas[currentDrawDatas.length - 1].isNeedRedraw = false
                dp.resetDrawCurrentPage()
                return
            }

            var txt = data.draw.label;
            var x = data.draw.x * canvas.width;
            var y = data.draw.y * canvas.height;

            context.font = data.draw.size * canvas.width / data.width + 'pt SimSun';
            context.fillStyle = getHexRGB(data.color);
            context.textBaseline = 'top';
            context.textAlign = 'left';
            context.fillText(txt, x, y);
        },

        /**
         * type
         * 0:清屏
         * 1:清除上一步
         * 2:绘线
         * 3:矩形
         * 4:圆形
         * 5:文字
         * 6:删除整个文档
         * 7:清理文档每一页的画笔数据
         * 8:删除所有文档，以及所有文档的画笔数据
         * 9:清除指定ID的画笔数据
         *
         * page 第几页
         * thickness 线条粗细 默认1
         * color 线条颜色 ，文字颜色默认0
         * alpha 透明度 默认1
         * draw 数据坐标
         * docid 文档id
         * width 文档宽
         * height 文档高
         * */
        draw: function(data, notCache) {
            if (typeof data === "string") {
                data = JSON.parse(data);
            }

            if (!data) {
                return;
            }

            var k = data.docid + '_' + data.page;

            var dp = this;
            if (!dp.caches[k]) {
                dp.caches[k] = {
                    doc: {
                        id: data.docid,
                        num: data.page
                    },
                    draws: []
                };
            }

            if (!notCache && data.type != 9) {
                // 去除重复drawid文字
                if (data.type === 5) {
                    var currentDraws = dp.caches[k].draws
                    if (currentDraws.length > 0) {
                        var currentDrawText = currentDraws[currentDraws.length - 1]
                        if (currentDrawText.drawid == data.drawid) {
                            dp.caches[k].draws.pop()
                            data.isNeedRedraw = true
                            dp.caches[k].draws.push(data)
                        } else {
                            dp.caches[k].draws.push(data)
                        }
                    } else {
                        dp.caches[k].draws.push(data)
                    }
                } else {
                    dp.caches[k].draws.push(data);
                }
            }


            if (dp.caches[k].needUpdatedHeight) {
                var canvas = document.getElementById(dp.id);
                canvas.height = canvas.width * data.height / data.width;
                dpCenter();
                // 更新一次就不需要再更新
                dp.caches[k].needUpdatedHeight = false;
            }

            var c = dp.caches[dp.currentDocKey];
            if (!c || c.doc.id != data.docid || c.doc.num != data.page) {
                return;
            }


            switch (data.type) {
                case DRAW_TYPE.CLEAR_SCREEN: // 清屏
                    this.clearScreen(data);
                    break;

                case DRAW_TYPE.CLEAR_PREV: // 清除上一步
                    this.clearPrev(data);
                    break;

                case DRAW_TYPE.DRAW_LINE: // 绘线
                    this.drawLine(data);
                    break;

                case DRAW_TYPE.DRAW_RECT: // 矩形
                    this.drawRect(data);
                    break;

                case DRAW_TYPE.DRAW_ARC: // 圆形
                    this.drawArc(data);
                    break;

                case DRAW_TYPE.DRAW_TXT: // 文字
                    this.drawTxt(data);
                    break;

                case DRAW_TYPE.DELETE_DOC: // 删除整个文档
                    this.deleteDoc(data);
                    break;

                case DRAW_TYPE.CLEAR_DOC_DRAWS: // 清理文档每一页的画笔数据
                    this.clearDocDraws();
                    break;

                case DRAW_TYPE.DELETE_WHOLE_DOC_AND_DRAW: // 删除所有文档，以及所有文档的画笔数据
                    this.deleteWholeDocAndDraw(data);
                    break;

                case DRAW_TYPE.DELETE_DRAW_BY_ID: // 清除指定ID的画笔数据
                    this.deleteDrawById(data);
                    break;

                default:
                    break;
                    // throw new Error('unknow draw type');
            }
        }
    };

    window.DrawPanel = DrawPanel;

})(window, document, undefined);