/* global Fql */

Fql.Condition.Fiche = function (data) {
    this.operator = Fql.LOGICALOPERATOR_AND;
    this.ficheQueryArray = new Array();
    this.custom = {};
    if (data) {
        if (Array.isArray(data)) {
            this.addFicheQueries(data);
        } else if (!data.hasOwnProperty("queries")) {
            this.addFicheQueries(data);
        } else {
            for(let key in data) {
                let value = data[key];
                switch(key)  {
                    case "operator":
                        this.setOperator(value);
                        break;
                    case "queries":
                        this.addFicheQueries(value);
                        break;
                    default:
                        this.custom[key] = value;
                }
            }
        }
    }
};

Fql.Condition.Fiche.prototype.addFicheQueries = function (value) {
    if (Array.isArray(value)) {
        for(let val of value) {
            if (val) {
                if (val instanceof Fql.FicheQuery) {
                    this.ficheQueryArray.push(val);
                } else {
                    this.ficheQueryArray.push(new Fql.FicheQuery(val));
                }
            }
        }
    } else if (value instanceof Fql.FicheQuery) {
        this.ficheQueryArray.push(value);
    } else {
        this.ficheQueryArray.push(new Fql.FicheQuery(value));
    }
    return this;
};

Fql.Condition.Fiche.prototype.setOperator = function (operator) {
    switch(operator) {
        case Fql.LOGICALOPERATOR_OR:
            this.operator = Fql.LOGICALOPERATOR_OR;
            break;
        default:
            this.operator = Fql.LOGICALOPERATOR_AND;
    }
};

Fql.Condition.Fiche.prototype.toXml = function (indent) {
    if ((!indent) && (indent !== 0)) {
        indent = -999;
    }
    var xml = '';
    if (this.ficheQueryArray.length > 1) {
        _indent();
        xml += '<fiche-query-logic operator="' + Fql.escape(this.operator) + '"/>';
    }
    for(let ficheQuery of this.ficheQueryArray) {
        if ((ficheQuery) && (ficheQuery.toXml)) {
            xml += ficheQuery.toXml(indent);
        }
    }
    return xml;
    
    function _indent() {
        if (indent >= 0) {
            xml += '\n';
            for(let i = 0; i < indent; i++) {
                xml += '\t';
            }
        }
    }
 
 };
  
