(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "../core/AtomDisposableList", "../core/AtomOnce", "../core/AtomUri"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var AtomDisposableList_1 = require("../core/AtomDisposableList");
    var AtomOnce_1 = require("../core/AtomOnce");
    var AtomUri_1 = require("../core/AtomUri");
    /**
     * Binds property of View Model to URL Parameter, it can read query string as well,
     * however it will only persist value in hash
     * @param vm View Model
     * @param name property name of View Model
     * @param urlParameter url parameter name
     */
    function bindUrlParameter(vm, name, urlParameter) {
        if (!name) {
            return;
        }
        if (!urlParameter) {
            return;
        }
        var a = vm;
        var paramDisposables = (a.mUrlParameters || (a.mUrlParameters = {}));
        var old = paramDisposables[name];
        if (old) {
            old.dispose();
            paramDisposables[name] = null;
        }
        var disposables = new AtomDisposableList_1.AtomDisposableList();
        var updater = new AtomOnce_1.AtomOnce();
        disposables.add(a.setupWatch([
            ["app", "url", "hash", urlParameter],
            ["app", "url", "query", urlParameter]
        ], function (hash, query) {
            updater.run(function () {
                var value = hash || query;
                if (value) {
                    // tslint:disable-next-line:triple-equals
                    if (value != vm[name]) {
                        vm[name] = value;
                    }
                }
            });
        }));
        disposables.add(a.setupWatch([[name]], function (value) {
            updater.run(function () {
                var url = vm.app.url || (vm.app.url = new AtomUri_1.AtomUri(""));
                url.hash[urlParameter] = value;
                vm.app.syncUrl();
            });
        }));
        paramDisposables[name] = disposables;
        return vm.registerDisposable(disposables);
    }
    exports.default = bindUrlParameter;
});
//# sourceMappingURL=bindUrlParameter.js.map