"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
var omit_base_props_1 = require("@monstrosity/utilities/type-manipulation/omit-base-props");
exports.propKeys = [
    'loadingView',
    'errorView',
    'importStatement',
    'importName',
    'fallbackStatement',
    'onLoaded',
    'onError',
];
function ExtractAndSet(props, importGroup, setView, importName, onLoaded) {
    var ResolvedImport = importGroup[importName || 'default'];
    var importProps = omit_base_props_1.omitBaseProps(props, exports.propKeys);
    setView(react_1.default.createElement(ResolvedImport, __assign({}, importProps)));
    if (onLoaded)
        onLoaded();
}
function Loadable(props) {
    var loadingView = props.loadingView, errorView = props.errorView, importStatement = props.importStatement, importName = props.importName, fallbackStatement = props.fallbackStatement, onLoaded = props.onLoaded, onError = props.onError;
    var _a = __read(react_1.default.useState(loadingView), 2), view = _a[0], setView = _a[1];
    var load = function () {
        importStatement()
            .then(function (resolvedImportGroup) {
            ExtractAndSet(props, resolvedImportGroup, setView, importName, onLoaded);
        })
            .catch(function (e) {
            try {
                ExtractAndSet(props, fallbackStatement(), setView, importName, onLoaded);
            }
            catch (error) {
                setView(errorView || error.toString());
            }
            if (onError)
                onError();
        });
    };
    react_1.default.useEffect(function () { return load(); }, []); /* [] Run Once */
    return view;
}
exports.Loadable = Loadable;
