var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
(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/AtomBinder", "../../core/AtomLoader", "../../core/AtomUri", "../../services/NavigationService", "../../view-model/AtomWindowViewModel", "../core/AtomUI", "../styles/AtomFrameStyle", "./AtomControl"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AtomFrame = void 0;
    var AtomBinder_1 = require("../../core/AtomBinder");
    var AtomLoader_1 = require("../../core/AtomLoader");
    var AtomUri_1 = require("../../core/AtomUri");
    var NavigationService_1 = require("../../services/NavigationService");
    var AtomWindowViewModel_1 = require("../../view-model/AtomWindowViewModel");
    var AtomUI_1 = require("../core/AtomUI");
    var AtomFrameStyle_1 = require("../styles/AtomFrameStyle");
    var AtomControl_1 = require("./AtomControl");
    /**
     * Creates and hosts an instance of AtomControl available at given URL. Query string parameters
     * from the url will be passed to view model as initial property values.
     *
     * By default stack is turned off, so elements and controls will be destroyed when new control is hosted.
     */
    var AtomFrame = /** @class */ (function (_super) {
        __extends(AtomFrame, _super);
        function AtomFrame(app, e) {
            return _super.call(this, app, e || document.createElement("section")) || this;
        }
        Object.defineProperty(AtomFrame.prototype, "canGoBack", {
            get: function () {
                return this.stack.length ? true : false;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AtomFrame.prototype, "url", {
            get: function () {
                return this.mUrl;
            },
            set: function (value) {
                var _this = this;
                if (this.mUrl === value) {
                    return;
                }
                if (value === undefined) {
                    return;
                }
                this.runAfterInit(function () {
                    _this.app.runAsync(function () { return _this.loadForReturn(value === null ? null : new AtomUri_1.AtomUri(value), true); });
                });
            },
            enumerable: false,
            configurable: true
        });
        AtomFrame.prototype.onBackCommand = function () {
            return __awaiter(this, void 0, void 0, function () {
                var ctrl;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.stack.length) {
                                // tslint:disable-next-line: no-console
                                console.warn("FrameStack is empty !!");
                                return [2 /*return*/];
                            }
                            ctrl = this.current;
                            if (!ctrl) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.navigationService.remove(ctrl)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * This will pop page from the stack and set as current
         * @param windowClosed true if current page was closed by User Action
         */
        AtomFrame.prototype.popStack = function (windowClosed) {
            if (!this.stack.length) {
                // tslint:disable-next-line: no-console
                console.warn("FrameStack is empty !!");
                return;
            }
            var last = this.stack.pop();
            AtomBinder_1.AtomBinder.refreshItems(this.stack);
            this.current = last.page;
            this.current.element.style.display = "";
            this.setUrl(last.url);
            if (this.saveScrollPosition) {
                setTimeout(function () {
                    window.scrollTo(0, last.scrollY);
                }, 200);
            }
        };
        AtomFrame.prototype.canChange = function () {
            var c = this.current;
            if (!c) {
                return Promise.resolve(true);
            }
            return this.navigationService.remove(c);
        };
        AtomFrame.prototype.push = function (ctrl) {
            if (this.current) {
                if (this.keepStack) {
                    this.current.element.style.display = "none";
                    this.stack.add({
                        url: this.current._$_url,
                        page: this.current,
                        scrollY: this.navigationService.screen.scrollTop
                    });
                }
                else {
                    if (this.current === ctrl) {
                        return;
                    }
                    var c1 = this.current;
                    var e1 = c1.element;
                    if (e1) {
                        this.navigationService.remove(c1);
                    }
                }
            }
            var element = ctrl.element;
            var e = this.pagePresenter || this.element;
            (e).appendChild(element);
            this.current = ctrl;
            if (this.saveScrollPosition) {
                window.scrollTo(0, 0);
            }
        };
        AtomFrame.prototype.load = function (url, clearHistory) {
            return __awaiter(this, void 0, void 0, function () {
                var _a, view, disposables, urlString, e;
                var _this = this;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!clearHistory) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.canChange()];
                        case 1:
                            if (!(_b.sent())) {
                                return [2 /*return*/];
                            }
                            _b.label = 2;
                        case 2: return [4 /*yield*/, AtomLoader_1.AtomLoader.loadView(url, this.app, true, function () { return new AtomWindowViewModel_1.AtomWindowViewModel(_this.app); })];
                        case 3:
                            _a = _b.sent(), view = _a.view, disposables = _a.disposables;
                            urlString = url.toString();
                            view._$_url = urlString;
                            this.push(view);
                            e = view.element;
                            this.navigationService.currentTarget = e;
                            this.setUrl(urlString);
                            disposables.add({
                                dispose: function () {
                                    e.innerHTML = "";
                                    e.remove();
                                    _this.navigationService.currentTarget = null;
                                    _this.popStack(true);
                                }
                            });
                            return [2 /*return*/, view];
                    }
                });
            });
        };
        AtomFrame.prototype.toUpperCase = function (s) {
            return s.split("-")
                .filter(function (t) { return t; })
                .map(function (t) { return t.substr(0, 1).toUpperCase() + t.substr(1); })
                .join("");
        };
        AtomFrame.prototype.setUrl = function (urlString) {
            this.mUrl = urlString;
            AtomBinder_1.AtomBinder.refreshValue(this, "url");
            AtomBinder_1.AtomBinder.refreshValue(this, "canGoBack");
        };
        AtomFrame.prototype.loadForReturn = function (url, clearHistory) {
            return __awaiter(this, void 0, void 0, function () {
                var hasHistory, page, ex_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            hasHistory = this.keepStack;
                            this.keepStack = !clearHistory;
                            if (url === null) {
                                if (hasHistory && clearHistory) {
                                    this.clearStack();
                                }
                                return [2 /*return*/];
                            }
                            return [4 /*yield*/, this.load(url, clearHistory)];
                        case 1:
                            page = _a.sent();
                            if (hasHistory) {
                                if (clearHistory) {
                                    this.clearStack();
                                }
                            }
                            _a.label = 2;
                        case 2:
                            _a.trys.push([2, 4, , 5]);
                            return [4 /*yield*/, page.returnPromise];
                        case 3: return [2 /*return*/, _a.sent()];
                        case 4:
                            ex_1 = _a.sent();
                            // this will prevent warning in chrome for unhandled exception
                            if ((ex_1.message ? ex_1.message : ex_1) === "cancelled") {
                                // tslint:disable-next-line: no-console
                                console.warn(ex_1);
                                return [2 /*return*/];
                            }
                            // throw new Error( ex.stack ? (ex + "\r\n" + ex.stack ) : ex);
                            throw ex_1;
                        case 5: return [2 /*return*/];
                    }
                });
            });
        };
        AtomFrame.prototype.clearStack = function () {
            // clear stack... irrespective of cancellation !!
            for (var _i = 0, _a = this.stack; _i < _a.length; _i++) {
                var iterator = _a[_i];
                var e = iterator.page.element;
                if (e) {
                    iterator.page.dispose();
                    e.innerHTML = "";
                    e.remove();
                }
            }
            this.stack.clear();
        };
        AtomFrame.prototype.preCreate = function () {
            var _this = this;
            this.name = null;
            this.stack = [];
            this.keepStack = false;
            this.current = null;
            this.currentDisposable = null;
            this.saveScrollPosition = false;
            this.navigationService = this.app.resolve(NavigationService_1.NavigationService);
            this.defaultControlStyle = AtomFrameStyle_1.default;
            this.pagePresenter = null;
            this.mUrl = null;
            AtomUI_1.AtomUI.assignID(this.element);
            this.runAfterInit(function () {
                _this.setPrimitiveValue(_this.element, "styleClass", _this.controlStyle.name);
            });
            this.backCommand = function () { return _this.app.runAsync(function () { return _this.onBackCommand(); }); };
            // hook navigation...
            var d = this.navigationService.registerNavigationHook(function (url, _a) {
                var target = _a.target, clearHistory = _a.clearHistory, cancelToken = _a.cancelToken;
                if (_this.name) {
                    if (target !== _this.name) {
                        return undefined;
                    }
                }
                else {
                    if (target !== "frame"
                        && url.protocol !== "frame:") {
                        return undefined;
                    }
                }
                if (cancelToken) {
                    cancelToken.registerForCancel(function () {
                        _this.backCommand();
                    });
                }
                return _this.loadForReturn(url, clearHistory);
            });
            this.registerDisposable(d);
        };
        return AtomFrame;
    }(AtomControl_1.AtomControl));
    exports.AtomFrame = AtomFrame;
});
//# sourceMappingURL=AtomFrame.js.map