"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
const core_1 = require("@angular-devkit/core");
const Observable_1 = require("rxjs/Observable");
const virtual_1 = require("../tree/virtual");
/**
 * When a rule or source returns an invalid value.
 */
class InvalidRuleResultException extends core_1.BaseException {
    constructor(value) {
        let v = 'Unknown Type';
        if (value === undefined) {
            v = 'undefined';
        }
        else if (value === null) {
            v = 'null';
        }
        else if (typeof value == 'function') {
            v = `Function()`;
        }
        else if (typeof value != 'object') {
            v = `${typeof value}(${JSON.stringify(value)})`;
        }
        else {
            if (Object.getPrototypeOf(value) == Object) {
                v = `Object(${JSON.stringify(value)})`;
            }
            else if (value.constructor) {
                v = `Instance of class ${value.constructor.name}`;
            }
            else {
                v = 'Unknown Object';
            }
        }
        super(`Invalid rule or source result: ${v}.`);
    }
}
exports.InvalidRuleResultException = InvalidRuleResultException;
function callSource(source, context) {
    const result = source(context);
    if (result instanceof virtual_1.VirtualTree) {
        return Observable_1.Observable.of(result);
    }
    else if (result instanceof Observable_1.Observable) {
        return result;
    }
    else {
        throw new InvalidRuleResultException(result);
    }
}
exports.callSource = callSource;
function callRule(rule, input, context) {
    return input.mergeMap(i => {
        const result = rule(i, context);
        if (result instanceof virtual_1.VirtualTree) {
            return Observable_1.Observable.of(result);
        }
        else if (result instanceof Observable_1.Observable) {
            return result;
        }
        else {
            throw new InvalidRuleResultException(result);
        }
    });
}
exports.callRule = callRule;
//# sourceMappingURL=data:application/json;base64,[encoded data, 5532 characters]