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

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

  var imgs = using('pages/chat/emoji').New().names;
  var cacheImg = [];
  var symbol = '';
  var QT;

    function removeStyleAttr(html) {
        return html.replace(/\sstyle=".*?"/g, '');
    }
    function removeTag(html){
        return html.replace(/<.*?>/g, '');
    }
    function writeText(t) {
        if(t){
            window.inputbox.insert_text(t);
        }
    }
    function writeImg(t) {
        t = '/' + t;
        window.inputbox.insert_image(QT.get_emofile_onshortcut(t), t);
    }
    function write(t){
        var len = cacheImg.length;
        var i, text;
        if(len > 0){
            text = t.split(symbol);
            for(i = 0; i < len; i++){
                writeText(text[i]);
                writeImg(cacheImg[i]);
            }
            writeText(text[i]);
        }else{
            writeText(t);
        }
    }
    function convertImg(t) {
        var i, len, temp;
        var match = t.match(/<img src="static\/images\/def\/def_[a-z]{1,10}\.gif">/g);

        if(match){
            len = match.length;
            for(i = 0; i < len; i++){
                temp = match[i].replace('<img src="static\/images\/def\/def_', '').replace('.gif">', '');
                t = t.replace(match[i], symbol);
                cacheImg.push(temp);
            }
        }
        return t;
    }
    function convertSpecial(t){
        return t.replace(/<br>/g, '\n');
    }
    function getUniqueSymbol(text) {
        var temp = '@#$' + parseInt(Math.random() * 10000000) + '@#$';
        while (text.indexOf(temp) > 0) {
            temp = '@#$' + parseInt(Math.random() * 10000000) + '@#$';
        }
        return temp;
    }



    self.bindQT = function(qt){
    QT = qt;
  };

  self.run = function (html) {
    cacheImg = [];

    symbol = getUniqueSymbol(html);
    html = removeStyleAttr(html);
    html = convertImg(html);
    html = convertSpecial(html);
    html = removeTag(html);

    write(html);
  };


  self.func(function(){

  })
});