/**
 * @author pei-qiao.peng
 * @date   2015/1/15.
 * @email  ppq1991@gmail.com
 * @github https://github.com/ppq1991/
 * @blog   http://pengpeiqiao.tk/
 */

Class(function (extend, using, self) {
  'use strict';

  var model = using('pages/chat/emoji');
  var pmMsgLastSend = {
    name: '',
    time: 0
  };

    // functions
    function getTimeString(time) {
        var d = new Date();
        if (time) {
            d = new Date(time * 1000);
        }
        var hh = d.getHours();
        var mm = d.getMinutes();
        var ss = d.getSeconds();
        return fix(hh) + ':' + fix(mm) + ':' + fix(ss);
    }

    function getColorByIndex(index) {
        var hex_color;
        switch (index) {
            case 0:
                hex_color = '#425354';
                break;
            case 1:
                hex_color = '#de5b21';
                break;
            case 2:
                hex_color = '#f9a80b';
                break;
            case 3:
                hex_color = '#f41d0c';
                break;
            case 4:
                hex_color = '#ff0099';
                break;
            case 5:
                hex_color = '#cb0cf4';
                break;
            case 6:
                hex_color = '#0065fe';
                break;
            case 7:
                hex_color = '#017f9f';
                break;
            case 8:
                hex_color = '#09970c';
                break;
            default:
                hex_color = "#425354";
        }
        return hex_color;
    }

    function fix(n) {
        n = n + '';
        if (n.length < 2) {
            n = '0' + n;
        }
        return n;
    }

    function setFontStyle($p, n) {
        if (n & 1) {
            $p.css('font-weight', 'bold');
        }
        if (n & 2) {
            $p.css('font-style', 'italic');
        }
        if (n & 4) {
            $p.css('text-decoration', 'underline');
        }
    }

    function pretreatment(content) {
        var symbol = getUniqueSymbol(content);
        var links = [];
        var i, len;
        var match = content.match(/<a.*?href="ghop">.*?<\/a>/g);
        if (match) {
            for (i = 0, len = match.length; i < len; i++) {
                content = content.replace(match[i], symbol);
                links[i] = match[i];
            }
            content = convertEmojiStringToImg(convertLink(encodeHtml(content)));
            for (i = 0; i < len; i++) {
                content = content.replace(symbol, links[i]);
            }
            return content;
        } else {
            return convertEmojiStringToImg(convertLink(encodeHtml(content)));
        }
    }

    function encodeHtml(html) {
        return $('<div>').text(html).html();
    }

    function convertSpecialSymbol(html) {
        return html.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;');
    }

    function convertEmojiStringToImg(html) {
        var i, names = model.names, len = names.length;
        for (i = 0; i < len; i++) {
            html = html.replace(new RegExp('/' + names[i], 'g'), '<img src="static/images/def/def_' + names[i] + '.gif">');
        }
        return html;
    }

    function convertLink(html) {
        var reg = /(https?:\/\/[\S]+)|(\w+?\.\w+?\.[\S]+)/g;
        var match = html.match(reg);
        var symbol = getUniqueSymbol(html);
        var i, len, links = [];
        if (match) {
            for (i = 0, len = match.length; i < len; i++) {
                html = html.replace(match[i], symbol);
                if (/https?:\/\//.test(match[i])) {
                    links[i] = '<a href="' + match[i] + '" target="_blank">' + match[i] + '</a>';
                } else {
                    links[i] = '<a href="http://' + match[i] + '" target="_blank">' + match[i] + '</a>';
                }

            }
            html = convertSpecialSymbol(html);
            for (i = 0, len; i < len; i++) {
                html = html.replace(symbol, links[i]);
            }
        }else{
            html = convertSpecialSymbol(html);
        }
        return html;
    }

    function getUniqueSymbol(text) {
        var temp = '@#$' + parseInt(Math.random() * 10000000) + '@#$';
        while (text.indexOf(temp) > 0) {
            temp = '@#$' + parseInt(Math.random() * 10000000) + '@#$';
        }
        return temp;
    }

  self.getTest = function (msg) {
    return $('<p>').text(msg);
  };

  self.getSysMsg = function (icon, color, text) {
    var msg = $('<p>');
    if (icon === 1) {
      msg.addClass('msg-sys-1');
    }
    if (icon === 2) {
      msg.addClass('msg-sys-2');
    }
    msg.css('color', color);
    msg.html(pretreatment(text));
    return msg;
  };

  self.getconcatMicMsg = function(name, cookie) {
      var msg = $('<p>');
      msg.addClass('msg-sys-1');
      msg.html(("<div class='concatMic' cookie='"+cookie+"'>"+ name +"邀请你加入连麦。<span class='concatMic_ok enable'>同意</span> or <span class='concatMic_cancel enable'>拒绝</span></div>"));
      return msg;
  }

  self.getCurSpokesManMsg = function(json){

      if ($("#curSpokesManMsg").length)
          $("#curSpokesManMsg").remove();

      var msg = $('<div id="curSpokesManMsg" style="position: absolute; right: -20; top:10px">');
      var line1 = $('<p>').addClass('line-style-1').appendTo(msg);

      var name = json.sendusername;
      var sid = json.senduserid;
      var linkName = $('<span style="line-height: 16px; margin-left: 20px">').addClass('link-name').text(name).attr('data-sid', sid);

      var img = json.identityimg;
      line1.append($('<img style="width:16px;height:16px;-webkit-transform:rotateY(180deg);; display: block; position: absolute; top: 0px" src="static/images/horn.png"/>'))

      linkName.appendTo(line1);


      return msg;
  }

  self.getUserMsg = function (json) {
    var msg = $('<div style="padding:5px 0">');
    var line1 = $('<p style="position: relative">').addClass('line-style-1').appendTo(msg);
    var line2 = $('<p>').addClass('line-style-2').appendTo(msg);
    var spanTime = $('<span>');
    var name = json.sendusername;
    var sid = json.senduserid;
    var linkName = $('<span>').addClass('link-name').text(name).attr('data-sid', sid);
    var time = getTimeString();
    var color = getColorByIndex(json.fontcolor);
    var style = json.fontstyle;
    var img = json.identityimg;
    var content = json.content;

    setFontStyle(line2, style);

    if (img) {
      line1.css('background-image', 'url(static/images/role/' + img + ')');
    }

    linkName.appendTo(line1);
    if (json.origin == "webim"){
        $('<span title="该用户正在使用网页观看直播">').addClass('line-webim').appendTo(line1);
        spanTime.css({ "padding-left":21 })
        linkName.css("margin-right",5)
    }
    spanTime.text(time).appendTo(line1);
    content = pretreatment(content);
    //alert(content)
    line2.css('color', color).html(content);
    return msg;
  };

  self.getFlowerMsg = function (json) {
    var msg = $('<p>').addClass('line-style-3');
    var num = json.giftnum;
    var img = json.identityimg;
    var text = json.text;
    var sid = json.userid;
    var name = json.username;
    var img_w = json.giftwidth;
    var img_h = json.giftheight;


    var url = 'url("file:///' + json.gift + '")';
    var linkName = $('<span>').addClass('link-name').text(name).attr('data-sid', sid);
    var content = $('<span>').addClass('concat-text').text(text);
    var gift = $('<div>').addClass('img').css({'background-image': url});

    if (json.gift.indexOf("swf") != -1){
        gift = $('<embed wmode="transparent"  menu="false" type="application/x-shockwave-flash"></embed>').attr("src",'file:///'+json.gift).appendTo("<div style='float:left;' data-title='"+text+"'></div>")
        linkName.appendTo(msg);
        msg.append(linkName).append(content).append(gift);

        gift.css({
            width : json.giftwidth + 'px',
            height : json.giftheight + 'px'
        })
    } else {
        if (img) {
            msg.css('background-image', 'url(static/images/role/' + img + ')');
        }

        if(img_w < 32){
            img_w = 32;
        }

        //msg.css('line-height', img_h + 'px');

        gift.css({
            width : img_w + 'px',
            height : img_h + 'px'
        });
        linkName.appendTo(msg);
        msg.append(linkName).append(content).append(gift).append('<span>x</span><i>' + num + '</i>');
    }






    return msg;
  };

  self.getPmMsg = function (json) {
    var msg = $('<div>');
    var line1 = $('<p>').addClass('line-style-1').appendTo(msg);
    var line2 = $('<p>').addClass('line-style-4').appendTo(msg);
    var spanTime = $('<span>');
    var name = json.sendusername;
    var sid = json.senduserid;
    var linkName = $('<span>').addClass('link-name').text(name).attr('data-sid', sid);
    var time = getTimeString(json.sendtime);
    var color = getColorByIndex(json.fontcolor);
    var style = json.fontstyle;
    var img = json.identityimg;
    var content = json.content;

    if (name == pmMsgLastSend.name) {
      if ((new Date() - pmMsgLastSend.time) < 30000) {
        line1.remove();
      }
    }
    pmMsgLastSend.time = new Date();
    pmMsgLastSend.name = name;

    setFontStyle(line2, style);

    if (img) {
      line1.css('background-image', 'url(static/images/role/' + img + ')');
    }

    linkName.appendTo(line1);
    spanTime.text(time).appendTo(line1);
    content = pretreatment(content);
    //alert(content)
    line2.css('color', color).html(content);

    return msg;
  };

  self.func(function(){

  });
});