/* global Fql */

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

Fql.Condition.Motcle.prototype.addMotcleQueries = function (value) {
    if (Array.isArray(value)) {
        for(let val of value) {
            if (val) {
                if (val instanceof Fql.MotcleQuery) {
                    this.motcleQueryArray.push(val);
                } else {
                    this.motcleQueryArray.push(new Fql.MotcleQuery(val));
                }
            }
        }
    } else if (value instanceof Fql.MotcleQuery) {
        this.motcleQueryArray.push(value);
    } else {
        this.motcleQueryArray.push(new Fql.MotcleQuery(value));
    }
    return this;
};

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

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