/**
 * @license
 * Copyright 2021 Google Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
import { __extends, __read, __spreadArray, __values } from "tslib";
import { getDescriptor } from './observer';
/**
 * Mixin to add `MDCObserver` functionality to an optional base class.
 *
 * @deprecated Prefer MDCObserverFoundation for stricter closure compliance.
 * @template C Optional base class constructor type.
 * @param baseClass - Optional base class.
 * @return A class that extends the optional base class with `MDCObserver`
 *     functionality.
 */
export function mdcObserver(baseClass) {
    var _a, _b;
    if (baseClass === void 0) { baseClass = /** @class */ (function () {
        function class_1() {
        }
        return class_1;
    }()); }
    var unobserves = Symbol();
    return _b = /** @class */ (function (_super) {
            __extends(MDCObserver, _super);
            function MDCObserver() {
                var _this = _super !== null && _super.apply(this, arguments) || this;
                _this[_a] = [];
                return _this;
            }
            MDCObserver.prototype.observe = function (target, observers) {
                var e_1, _b;
                var _this = this;
                var cleanup = [];
                try {
                    for (var _c = __values(Object.keys(observers)), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var property = _d.value;
                        var observer = observers[property].bind(this);
                        cleanup.push(observeProperty(target, property, observer));
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                var unobserve = function () {
                    var e_2, _b;
                    try {
                        for (var cleanup_1 = __values(cleanup), cleanup_1_1 = cleanup_1.next(); !cleanup_1_1.done; cleanup_1_1 = cleanup_1.next()) {
                            var cleanupFn = cleanup_1_1.value;
                            cleanupFn();
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (cleanup_1_1 && !cleanup_1_1.done && (_b = cleanup_1.return)) _b.call(cleanup_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                    var index = _this[unobserves].indexOf(unobserve);
                    if (index > -1) {
                        _this[unobserves].splice(index, 1);
                    }
                };
                this[unobserves].push(unobserve);
                return unobserve;
            };
            MDCObserver.prototype.setObserversEnabled = function (target, enabled) {
                setObserversEnabled(target, enabled);
            };
            MDCObserver.prototype.unobserve = function () {
                var e_3, _b;
                try {
                    // Iterate over a copy since unobserve() will remove themselves from the
                    // array
                    for (var _c = __values(__spreadArray([], __read(this[unobserves]))), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var unobserve = _d.value;
                        unobserve();
                    }
                }
                catch (e_3_1) { e_3 = { error: e_3_1 }; }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                    }
                    finally { if (e_3) throw e_3.error; }
                }
            };
            return MDCObserver;
        }(baseClass)),
        _a = unobserves,
        _b;
}
var isTargetObservers = Symbol();
var isEnabled = Symbol();
var getObservers = Symbol();
/**
 * Observe a target's property for changes. When a property changes, the
 * provided `Observer` function will be invoked with the properties current and
 * previous values.
 *
 * The returned cleanup function will stop listening to changes for the
 * provided `Observer`.
 *
 * @template T The observed target type.
 * @template K The observed property.
 * @param target - The target to observe.
 * @param property - The property of the target to observe.
 * @param observer - An observer function to invoke each time the property
 *     changes.
 * @return A cleanup function that will stop observing changes for the provided
 *     `Observer`.
 */
export function observeProperty(target, property, observer) {
    var observerPrototype = installObserver(target);
    var observers = observerPrototype[getObservers](property);
    observers.push(observer);
    return function () {
        observers.splice(observers.indexOf(observer), 1);
    };
}
/**
 * Installs a `TargetObservers` for the provided target (if not already
 * installed).
 *
 * A target's `TargetObservers` is installed as a Proxy on the target's
 * prototype.
 *
 * @template T The observed target type.
 * @param target - The target to observe.
 * @return The installed `TargetObservers` for the provided target.
 */
function installObserver(target) {
    var e_4, _a, e_5, _b;
    var prototype = Object.getPrototypeOf(target);
    if (prototype[isTargetObservers]) {
        return prototype;
    }
    // Proxy prototypes will not trap plain properties (not a getter/setter) that
    // are already defined. They only work on new plain properties.
    // We can work around this by deleting the properties, installing the Proxy,
    // then re-setting the properties.
    var existingKeyValues = new Map();
    var keys = Object.getOwnPropertyNames(target);
    try {
        for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
            var key = keys_1_1.value;
            var descriptor = getDescriptor(target, key);
            if (descriptor && descriptor.writable) {
                existingKeyValues.set(key, descriptor.value);
                delete target[key];
            }
        }
    }
    catch (e_4_1) { e_4 = { error: e_4_1 }; }
    finally {
        try {
            if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
        }
        finally { if (e_4) throw e_4.error; }
    }
    var proxy = new Proxy(Object.create(prototype), {
        get: function (target, key, receiver) {
            return Reflect.get(target, key, receiver);
        },
        set: function (target, key, newValue, receiver) {
            var e_6, _a;
            var isTargetObserversKey = key === isTargetObservers ||
                key === isEnabled || key === getObservers;
            var previous = Reflect.get(target, key, receiver);
            // Do not use receiver when setting the target's key. We do not want
            // to change whatever the target's inherent receiver is.
            Reflect.set(target, key, newValue);
            if (!isTargetObserversKey && proxy[isEnabled] &&
                newValue !== previous) {
                try {
                    for (var _b = __values(proxy[getObservers](key)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var observer = _c.value;
                        observer(newValue, previous);
                    }
                }
                catch (e_6_1) { e_6 = { error: e_6_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_6) throw e_6.error; }
                }
            }
            return true;
        }
    });
    proxy[isTargetObservers] = true;
    proxy[isEnabled] = true;
    var observersMap = new Map();
    proxy[getObservers] = function (key) {
        var observers = observersMap.get(key) || [];
        if (!observersMap.has(key)) {
            observersMap.set(key, observers);
        }
        return observers;
    };
    Object.setPrototypeOf(target, proxy);
    try {
        // Re-set plain pre-existing properties so that the Proxy can trap them
        for (var _c = __values(existingKeyValues.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {
            var _e = __read(_d.value, 2), key = _e[0], value = _e[1];
            target[key] = value;
        }
    }
    catch (e_5_1) { e_5 = { error: e_5_1 }; }
    finally {
        try {
            if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
        }
        finally { if (e_5) throw e_5.error; }
    }
    return proxy;
}
/**
 * Enables or disables all observers for a provided target. Changes to observed
 * properties will not call any observers when disabled.
 *
 * @template T The observed target type.
 * @param target - The target to enable or disable observers for.
 * @param enabled - True to enable or false to disable observers.
 */
export function setObserversEnabled(target, enabled) {
    var prototype = Object.getPrototypeOf(target);
    if (prototype[isTargetObservers]) {
        prototype[isEnabled] = enabled;
    }
}
//# sourceMappingURL=observer-proxy.js.map