ProspectDirector.Web.UI.Queries.ConditionResolver = Class.extend({

    _filter: null,

    init: function (options) {
        this.options = options;
        _filter = this.get_constraints().findById(options.filterId);
    },

    get_constraints: function () {
        return this.options.constraints;
    },

    get_constraint: function () {
        return _filter;
    },

    resolve: function () {

        var constraint = this.get_constraint(),
            parent = constraint.get_parent(),
            condition = null,
            inGroup = true;

        if (this.get_constraint().get_role() === "condition") {
            condition = this.get_constraint();
        }
        else {
            condition = this.resolveFilter(constraint);
        }

        if (!condition) {
            condition = this.resolveCondition(parent);
        }

        if (condition && parent) {
            inGroup = condition.get_id() === parent.get_id();
        }

        result = {
            constraint: constraint,
            condition: condition,
            inGroup: inGroup
        };

        return result;

    },

    resolveFilter: function (filter) {

        var result = null;
            lastFilter = this.isLastFilterInGroup(filter),
            siblingConditionCount = filter.get_parent().get_conditions().count();

        if (!lastFilter || (lastFilter && siblingConditionCount > 0)) {
            result = filter.get_parent();
        }

        return result;

    },

    resolveCondition: function (condition) {

        var result = null;

        if (!condition.get_parent()) {
            return null;
        }

        if (!this.isLastConditionInGroup(condition)) {
            result = condition.get_parent();
        }
        else {
            result = this.resolveCondition(condition.get_parent());
        }

        return result;

    },

    isLastFilterInGroup: function (filter) {

        var last = filter.get_parent().get_filters().last();

        return last && last.get_id() === filter.get_id();

    },

    isLastConditionInGroup: function (condition) {

        var last = condition.get_parent().get_conditions().last();

        return last && last.get_id() === condition.get_id();

    }

});