/* global OpenDocument */

/**
 * 
 * @constructor
 * @param {Object} settings
 */
OpenDocument.CsvWriter = function (settings) {
    this.text = "";
    this.delimiter = ",";
    if (settings) {
        for(let key in settings) {
            let value = settings[key];
            switch(key) {
                case "delimiter":
                    this.delimiter = value;
                    break;
            }
        }
    }
    this.newLine = true;
};

OpenDocument.CsvWriter.prototype.endRow = function () {
    this.text += "\n";
    this.newLine = true;
};

OpenDocument.CsvWriter.prototype.addEmptyCell = function (cell) {
    if (!cell) {
        cell = OpenDocument.Elements.Cell.EMPTY;
    }
    this.startCell(cell);
    this.endCell(cell);
};

OpenDocument.CsvWriter.prototype.addCell = function (cell) {
    var text = "";
    if (cell.isEmpty()) {
        this
                .addEmptyCell(cell);
    } else {
        this.startCell(cell);
        switch(cell.getType()) {
            case "number":
            case "currency":
               this.text += cell.getValue();
               break;
            case "date":
               this.text += "\"" + cell.getValue() + "\"" ;
               break;
            default:
                text += "\"";
                let next = false;
                for(let line of cell.textArray) {
                    if (next) {
                        text += "\n";
                    } else {
                        next = true;
                    }
                    _escape(line);
                }
                text += "\"";
                this.text += text; 
        }
    }
    
    function _escape(line) {
        for (let i = 0, len = line.length; i < len; i++) {
            let carac = line.charAt(i);
            switch (carac) {
                case '"':
                    text += "\"\"";
                    break;
                default:
                    text += carac;
            }
        }
    }
    
};

OpenDocument.CsvWriter.prototype.startCell = function (cell) {
    if (cell.emptyPrevious) {
        for(let i = 0; i < cell.emptyPrevious; i++) {
            this
                .addEmptyCell();
        }
    }
    if (cell.jump) {
        for(let i = 0; i < cell.jump; i++) {
            this
                .addEmptyCell();
        }
    }
    if (!this.newLine) {
        this.text += this.delimiter;
    } else {
        this.newLine = false;
    }
};

OpenDocument.CsvWriter.prototype.endCell = function (cell) {
    if (cell.colSpan > 1) {
        for(let i = 1; i < cell.colSpan; i++) {
            this
                .addEmptyCell();
        }
    }
    if (cell.emptyNext) {
        for(let i = 0; i < cell.emptyNext; i++) {
            this
                .addEmptyCell();
        }
    }
};