/* global Fql */

Fql.Condition.Subset = function (data) {
    this.withCurrent = false;
    this.isExclude = false;
    this.nameArray = new Array();
    this.custom = {};
    if (data) {
        if (typeof data === "string") {
            this.addSubsets(data);
        } else if (Array.isArray(data)) {
            this.addSubsets(data);
        } else if (typeof data === "object") {
            for(let key in data) {
                let value = data[key];
                switch(key)  {
                    case "current":
                        if (value) {
                            this.withCurrent  = true;
                        }
                        break;
                    case "exclude":
                        if (value) {
                            this.isExclude  = true;
                        }
                        break;
                    case "names":
                        if (value) {
                            this.addSubsets(value);
                        }
                        break;
                    default:
                        this.custom[key] = value;
                }
            }
        }
    }
};

Fql.Condition.Subset.NAME_REGEX = new RegExp('^([a-z][a-z0-9]*)$');

Fql.Condition.Subset.prototype.isAll = function () {
    return (this.nameArray.length === 0) && (!this.withCurrent);
};

Fql.Condition.Subset.prototype.addSubsets = function (value) {
    var array = Fql.toCleanArray(value);
    for(let token of array) {
        if (typeof token === "string") {
            switch(token) {
                case "_current":
                    this.withCurrent = true;
                    break;
                case "_exclude":
                    this.isExclude = true;
                    break;
                default:
                    if (token.match(Fql.Condition.Subset.NAME_REGEX)) {
                        this.nameArray.push(token);
                    }
            }
        }
    }
};

Fql.Condition.Subset.prototype.toXml = function (category, indent) {
    if ((!indent) && (indent !== 0)) {
        indent = -999;
    }
    var xml = '';
    if (this.isExclude) {
        _indent();
        xml += '<exclude/>';
    }
    if (this.withCurrent) {
        _indent();
        xml += '<current/>';
    }
    for(let name of this.nameArray) {
        _indent();
        xml += '<' + category + '>' + Fql.escape(name) + '</' + category + '>';
    }
    return xml;
    
    function _indent() {
        if (indent >= 0) {
            xml += '\n';
            for(let i = 0; i < indent; i++) {
                xml += '\t';
            }
        }
    }
    
};