import { QueryHandler } from './QueryHandler';
var MediaQuery = (function () {
    function MediaQuery(query, isUnconditional) {
        var _this = this;
        if (isUnconditional === void 0) { isUnconditional = false; }
        this.query = query;
        this.isUnconditional = isUnconditional;
        this.handlers = [];
        this.mql = window.matchMedia(query);
        this.listener = function (mql) {
            _this.mql = mql.currentTarget || mql;
            _this.assess();
        };
        this.mql.addListener(this.listener);
    }
    MediaQuery.prototype.addHandler = function (handler) {
        var qh = new QueryHandler(handler);
        this.handlers.push(qh);
        if (this.matches()) {
            qh.on();
        }
    };
    MediaQuery.prototype.removeHandler = function (handler) {
        var handlers = this.handlers;
        for (var i = 0; i < handlers.length; i++) {
            var h = handlers[i];
            if (h.equals(handler)) {
                h.destroy();
                handlers.splice(i, 1);
                break;
            }
        }
    };
    MediaQuery.prototype.matches = function () {
        return this.mql.matches || this.isUnconditional;
    };
    MediaQuery.prototype.clear = function () {
        this.handlers.forEach(function (h) {
            h.destroy();
        });
        this.mql.removeListener(this.listener);
        this.handlers.length = 0;
    };
    MediaQuery.prototype.assess = function () {
        var match = this.matches();
        this.handlers.forEach(function (handler) {
            match ? handler.on() : handler.off();
        });
    };
    return MediaQuery;
}());
export { MediaQuery };
