// Save status for response use later, use for unique multi-request to one
//
var iconv = require('iconv-lite');


var ResponseHolder = function(defEnc) {
    this.defaultEncoding = defEnc;
    this.statusCode = 200;
    this.headers = {};
    this.body = null;
};

ResponseHolder.prototype.setStatusCode = function(sc) {
    this.statusCode = sc;
};

ResponseHolder.prototype.setHeader = function(name, value) {
    this.headers[name] = value;
    if (name.toLowerCase() == 'content-type') {
        var p = value.indexOf('charset=');
        if (p > 0) {
            this.defaultEncoding = value.substring(p + 8);
        }
    }
};

var minify = function(html){
    var lines = html.split(/\r?\n/);
    var newlines = [];
    lines.forEach(function(line){
        var l = line.replace(/(^\s*)|(\s*$)/g,"");
        if(l.length > 0) {
            newlines.push(l);
        }
    });
    return newlines.join('\r\n');
};


ResponseHolder.prototype.setBody = function(body, enc) {
    if (Buffer.isBuffer(body)) {
        this.body = body;
    } else {
        _enc = enc || this.defaultEncoding;
        var _body = null;
        if (typeof(body) === 'string' || body instanceof String) {
            _body = body;
        } else {
            _body = '' + body;
        }
        // this.body = iconv.encode(_body, _enc);
        // 编码放到了xsp.js doScript；
        this.body=_body;
    }
};

ResponseHolder.prototype.writeTo = function(response) {
    response.statusCode = this.statusCode;
    var headers = this.headers;
    for (var prop in headers) {
        if (headers.hasOwnProperty(prop)) {
            response.setHeader(prop, headers[prop]);
        }
    }
    if (this.body && this.body.length) {
        response.setHeader('Content-Length', this.body.length);
    }
    response.end(this.body);
};

// for debug only
ResponseHolder.prototype.print = function(response) {
    console.log('StatusCode: %d', this.statusCode);
    var headers = this.headers;
    console.log('Headers:');
    for (var prop in headers) {
        if (headers.hasOwnProperty(prop)) {
            console.log("%s: %s", prop, headers[prop]);
        }
    }

    console.log('Body: %s', this.body);
};

// 去页头页尾
function removeHeaderAndTail(body){
    body=body.replace('<script src="http://www.pcauto.com.cn/global/wap/header_js/" charset="utf-8" class=" defer"></script>','');
    body=body.replace('<script src="http://www.pcauto.com.cn/global/wap/footer_js/" charset="utf-8" class=" defer"></script>','');
    return body;
}

module.exports.ResponseHolder = ResponseHolder;
module.exports.removeHeaderAndTail=removeHeaderAndTail;
