/* global Fql */

Fql.Condition.Range = function (data) {
    this.rangeArray = new Array();
    this.exclude = false;
    this.custom = {};
    if (data) {
        if (typeof data === "number") {
            this.addRanges(data + "");
        } else if (typeof data === "string") {
            this.addRanges(data);
        } else if (Array.isArray(data)) {
            this.addRanges(data);
        } else {
            for(let key in data) {
                let value = data[key];
                switch(key) {
                    case "exclude":
                        if (value) {
                            this.exclude = true;
                        } else {
                            this.exclude = false;
                        }
                        break;
                    case "values":
                        this.addRanges(value);
                        break;
                    default:
                        this.custom[key] = value;
                }
            }
        }
    }
};

Fql.Condition.Range.prototype.isEmpty = function () {
    return (this.rangeArray.length === 0);
};

Fql.Condition.Range.prototype.addRanges = function (values) {
    let array;
    if (typeof values === "string") {
        array = values.split(/[;,]/);
    } else if (Array.isArray(values)) {
        array = values;
    } else {
        array = [values.toString()];
    }
    if (array) {
        for(let token of array) {
            token = token.toString().trim();
            if (token.length > 0) {
                this.rangeArray.push(token);
            }
        }
    }
    return this;
};

Fql.Condition.Range.prototype.addRange = function (start, end) {
    if (!end) {
        this.rangeArray.push(start);
    } else if (start < 1) {
       this.rangeArray.push('-' + end);
    } else if (end < 1) {
        this.rangeArray.push(start + '-');
    } else {
        this.rangeArray.push(start + '-' + end);
    }
    return this;
};

Fql.Condition.Range.prototype.toText = function (withExclude) {
    let length = this.rangeArray.length;
    if (length === 0) {
        return "";
    }
    let result = "";
    if ((withExclude) && (this.exclude)) {
        result += '!';
    }
    for(let i = 0; i < length; i++) {
        if (i > 0) {
            result += ';';
        }
        result += this.rangeArray[i];
    }
    return result;
};

Fql.Condition.Range.prototype.toXml = function (tagName, indent) {
    if ((!indent) && (indent !== 0)) {
        indent = -999;
    }
    if (this.isEmpty()) {
        return "";
    }
    var xml = '';
    _indent();
    xml += '<' + tagName;
    if (this.exclude) {
        xml += ' exclude="true"';
    }
    xml += '>';
    xml += Fql.escape(this.toText());
    xml += '</' + tagName + '>';
    return xml;
    
    
    function _indent() {
        if (indent >= 0) {
            xml += '\n';
            for(let i = 0; i < indent; i++) {
                xml += '\t';
            }
        }
    }
    
};
