/* global Fql */

Fql.Condition.Period = function (data) {
    this.onCreationDate = false;
    this.onModificationDate = false;
    this.fieldArray = new Array();
    this.start = Fql.DATE_ANY;
    this.end = Fql.DATE_SAME;
    this.custom = {};
    if (data) {
        for(let key in data) {
            let value = data[key];
            switch(key) {
                case "start":
                    this.start = value;
                    break;
                case "end":
                    this.end = value;
                    break;
                case "scope":
                    let tmparray = Fql.toCleanArray(value);
                    for(let token of tmparray) {
                        switch(token) {
                            case "creation":
                                this.onCreationDate = true;
                                break;
                            case "modification":
                                this.onModificationDate = true;
                                break;
                            default:
                                this.fieldArray.push(token);
                        }
                    }
                    break;
                default:
                    this.custom[key] = value;
            }
        }
    }
};

Fql.Condition.Period.prototype.addScope = function (scope) {
    if (scope === "creation") {
        this.onCreationDate = true;
    } else if (scope === "modification") {
        this.onModificationDate = true;
    } else {
        this.fieldArray.push(scope);
    }
};

Fql.Condition.Period.prototype.toText = function () {
    var text = "";
    text +=  this.start;
    if (this.end !== Fql.DATE_SAME) {
        text += " / " + this.end;
    }
    return text;
};

Fql.Condition.Period.prototype.toXml = function (indent) {
    if ((!indent) && (indent !== 0)) {
        indent = -999;
    }
    var xml = '';
    _indent();
    xml += '<period';
    xml += ' start="' + Fql.escape(this.start) + '"';
    if (this.end !== Fql.DATE_SAME) {
        xml += ' end="' + Fql.escape(this.end) + '"';
    }
    xml += '>';
    indent++;
    if (this.onCreationDate) {
         _indent();
         xml += '<chrono>creation</chrono>';
    }
    if (this.onModificationDate) {
         _indent();
         xml += '<chrono>modification</chrono>';
    }
    for(let field of this.fieldArray) {
        _indent();
        xml += '<field>' + Fql.escape(field) + '</field>';
    }
    indent--;
    _indent();
    xml += '</period>';
    return xml;
    
    
    function _indent() {
        if (indent >= 0) {
            xml += '\n';
            for(let i = 0; i < indent; i++) {
                xml += '\t';
            }
        }
    }
    
};