'use strict';

var util = require('util');
var Transform = require('stream').Transform;
var Block = require('./block');


function Parser(tasks, config, file) {
    Transform.call(this);

    this.tasks = tasks;
    this.config = config;
    this.file = file;
}
util.inherits(Parser, Transform);

var REGEX_BEGIN = /<!--\s*build:(\w+(-\w+)*)\s*-->/i;
var REGEX_END = /<!--\s*endbuild\s*-->/i;

Parser.prototype._transform = function (chunk, enc, done) {
    var content = chunk.toString('utf8');
    var linefeed = content.match(/[\r\n]+/);
    var lines = linefeed ? content.split(linefeed[0]) : [content];

    if (lines.length === 1) {
        content = content.split('><').join('>' + linefeed + '<');
        lines = content.split(linefeed);
        linefeed = '';
    }

    var buffered = [];

    var block = new Block(this.config, this.file);

    lines.forEach(function (line) {
        var block_begin = line.match(REGEX_BEGIN);
        var block_end = REGEX_END.test(line);

        if (block_begin) {
            var name = block_begin[1];
            var task = this.tasks[name];

            block.setTask(task);
            block.indent = line.match(/^\s*/)[0];
            if (this.config.keepBlockTags) {
                buffered.push(line);
            }
        } else if (block_end) {
            buffered = buffered.concat(block.compile());
            if (this.config.keepBlockTags) {
                buffered.push(line);
            }
        } else {
            block.inUse ? block.originals.push(line) : buffered.push(line);
        }
    }.bind(this));

    this.push(buffered.join(linefeed));
    done();
};

module.exports = Parser;

@@ -512,32 +512,45 @@
 d = 
-content.match(/%5B%5Cr%5Cn%5D+/)
+/%5Cr%5Cn/g.test(content) ? '%5Cr%5Cn' : '%5Cn'
 ;%0A  
@@ -596,19 +596,16 @@
 linefeed
-%5B0%5D
 ) : %5Bcon

Fix https://github.com/VFK/gulp-html-replace/issues/19