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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
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", "../../App", "../../core/AtomBinder", "../../core/AtomList", "../../core/AtomLoader", "../../core/AtomOnce", "../../core/AtomUri", "../../core/BindableProperty", "../../di/Inject", "../../services/NavigationService", "../../view-model/AtomViewModel", "../../view-model/AtomWindowViewModel", "../../view-model/bindUrlParameter", "../services/WindowService", "../styles/AtomTabbedPageStyle", "./AtomControl", "./AtomGridView", "./AtomItemsControl", "./AtomPage"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var App_1 = require("../../App");
    var AtomBinder_1 = require("../../core/AtomBinder");
    var AtomList_1 = require("../../core/AtomList");
    var AtomLoader_1 = require("../../core/AtomLoader");
    var AtomOnce_1 = require("../../core/AtomOnce");
    var AtomUri_1 = require("../../core/AtomUri");
    var BindableProperty_1 = require("../../core/BindableProperty");
    var Inject_1 = require("../../di/Inject");
    var NavigationService_1 = require("../../services/NavigationService");
    var AtomViewModel_1 = require("../../view-model/AtomViewModel");
    var AtomWindowViewModel_1 = require("../../view-model/AtomWindowViewModel");
    var bindUrlParameter_1 = require("../../view-model/bindUrlParameter");
    var WindowService_1 = require("../services/WindowService");
    var AtomTabbedPageStyle_1 = require("../styles/AtomTabbedPageStyle");
    var AtomControl_1 = require("./AtomControl");
    var AtomGridView_1 = require("./AtomGridView");
    var AtomItemsControl_1 = require("./AtomItemsControl");
    var AtomPage_1 = require("./AtomPage");
    var AtomTabbedPage = /** @class */ (function (_super) {
        __extends(AtomTabbedPage, _super);
        function AtomTabbedPage(app, e) {
            var _this = _super.call(this, app, e || document.createElement("section")) || this;
            _this.tabChannelName = "app";
            return _this;
        }
        Object.defineProperty(AtomTabbedPage.prototype, "windowService", {
            get: function () {
                return this.mWindowService || (this.mWindowService = this.resolve(WindowService_1.WindowService));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AtomTabbedPage.prototype, "selectedPage", {
            get: function () {
                return this.mSelectedPage;
            },
            set: function (value) {
                this.mSelectedPage = value;
                if (value && value.element) {
                    var pe = value.element.parentElement;
                    if (!pe || pe.parentElement !== this.presenter) {
                        var p = document.createElement("div");
                        var s = p.style;
                        p.className = "page-host";
                        s.position = "absolute";
                        s.left = s.right = s.top = s.bottom = "0";
                        p.appendChild(value.element);
                        this.presenter.appendChild(p);
                        var ve_1 = value;
                        value.bind(p, "styleDisplay", [["this", "selectedPage"]], false, function (v) { return v === ve_1 ? "" : "none"; }, this);
                    }
                }
                this.invalidate();
                this.windowService.currentTarget = value.element;
                AtomBinder_1.AtomBinder.refreshValue(this, "selectedPage");
            },
            enumerable: true,
            configurable: true
        });
        AtomTabbedPage.prototype.preCreate = function () {
            var _this = this;
            this.defaultControlStyle = AtomTabbedPageStyle_1.AtomTabbedPageStyle;
            this.runAfterInit(function () {
                _this.setPrimitiveValue(_this.element, "styleClass", _this.controlStyle.root);
            });
            this.localViewModel = this.resolve(AtomTabViewModel, function () { return ({ owner: _this }); });
            this.titleTemplate = TitleItemTemplateCreator(this);
            this.columns = "*";
            this.rows = "30,*";
            var ul = new AtomItemsControl_1.AtomItemsControl(this.app, document.createElement("div"));
            this.append(ul);
            ul.allowMultipleSelection = false;
            ul.allowSelectFirst = true;
            ul.bind(ul.element, "itemTemplate", [["this", "titleTemplate"]], false, null, this);
            ul.bind(ul.element, "items", [["localViewModel", "pages"]]);
            ul.bind(ul.element, "selectedItem", [["localViewModel", "selectedPage"]], true);
            // const presenter = new AtomContentControl(this.app, document.createElement("section"));
            // this.append(presenter);
            // presenter.setPrimitiveValue(presenter.element, "row", "1");
            // presenter.bind(presenter.element, "content", [["localViewModel", "selectedPage"]]);
            this.presenter = document.createElement("div");
            this.append(this.presenter);
            this.presenter.classList.add("presenter");
            this.presenter.row = "1";
            this.bind(this.element, "selectedPage", [["localViewModel", "selectedPage"]]);
            this.registerDisposable(this.windowService.registerHostForWindow(function (e) { return _this.getParentHost(e); }));
        };
        AtomTabbedPage.prototype.getParentHost = function (e) {
            var pe = e._logicalParent || e.parentElement;
            if (pe === this.presenter) {
                return e;
            }
            if (!pe) {
                return null;
            }
            return this.getParentHost(pe);
        };
        __decorate([
            BindableProperty_1.BindableProperty,
            __metadata("design:type", String)
        ], AtomTabbedPage.prototype, "tabChannelName", void 0);
        __decorate([
            BindableProperty_1.BindableProperty,
            __metadata("design:type", Object)
        ], AtomTabbedPage.prototype, "titleTemplate", void 0);
        return AtomTabbedPage;
    }(AtomGridView_1.AtomGridView));
    exports.AtomTabbedPage = AtomTabbedPage;
    // tslint:disable-next-line:variable-name
    function TitleItemTemplateCreator(__creator) {
        return /** @class */ (function (_super) {
            __extends(TitleItemTemplate, _super);
            function TitleItemTemplate() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            TitleItemTemplate.prototype.create = function () {
                var _this = this;
                // this.bind(this.element, "text", [["data", "title"]]);
                this.bind(this.element, "styleClass", [
                    ["data"],
                    ["localViewModel", "selectedPage"],
                    ["this", "controlStyle", "tabItem"],
                    ["this", "controlStyle", "selectedTabItem"]
                ], false, function (data, selectedPage, tabItem, selectedTabItem) {
                    var _a;
                    return (_a = {},
                        _a[tabItem.className] = true,
                        _a[selectedTabItem.className] = data === selectedPage,
                        _a);
                }, __creator);
                var divTitle = document.createElement("div");
                this.append(divTitle);
                this.bind(divTitle, "text", [["data", "title"]]);
                var closeButton = document.createElement("img");
                this.bind(closeButton, "styleClass", [["this", "controlStyle", "closeButton"]], false, null, __creator);
                // closeButton.textContent = "x";
                this.append(closeButton);
                this.bindEvent(closeButton, "click", function () { return __creator.localViewModel.closePage(_this.data); });
                this.bindEvent(divTitle, "click", function () {
                    _this.localViewModel.selectedPage = _this.data;
                });
            };
            return TitleItemTemplate;
        }(AtomControl_1.AtomControl));
    }
    var AtomTabViewModel = /** @class */ (function (_super) {
        __extends(AtomTabViewModel, _super);
        function AtomTabViewModel(app, owner) {
            var _this = _super.call(this, app) || this;
            _this.owner = owner;
            _this.pageUpdater = new AtomOnce_1.AtomOnce();
            _this.pages = new AtomList_1.AtomList();
            _this.bind(_this, "selectedUrl", _this, [["selectedPage"]], {
                fromSource: function (v) {
                    return v.tag;
                },
                fromTarget: function (v) {
                    if (!_this.pages) {
                        return null;
                    }
                    return _this.pages.find(function (p) { return p.tag === v; });
                }
            });
            bindUrlParameter_1.default(_this, "selectedUrl", "url");
            return _this;
        }
        AtomTabViewModel.prototype.init = function () {
            return __awaiter(this, void 0, void 0, function () {
                var ch, urls, urlState, _loop_1, this_1, _i, _a, iterator, d;
                var _this = this;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            ch = this.owner.tabChannelName;
                            this.storageKey = this.app.contextId + "_" + ch;
                            urls = sessionStorage.getItem(this.storageKey) || "null";
                            urlState = JSON.parse(urls) || {
                                name: name,
                                urls: [],
                                selectedUrl: null
                            };
                            _loop_1 = function (iterator) {
                                var page;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, this_1.loadPage(new AtomUri_1.AtomUri(iterator), true)];
                                        case 1:
                                            page = _a.sent();
                                            if (page.tag === urlState.selectedUrl) {
                                                this_1.pageUpdater.run(function () {
                                                    _this.selectedPage = page;
                                                });
                                            }
                                            return [2 /*return*/];
                                    }
                                });
                            };
                            this_1 = this;
                            _i = 0, _a = urlState.urls;
                            _b.label = 1;
                        case 1:
                            if (!(_i < _a.length)) return [3 /*break*/, 4];
                            iterator = _a[_i];
                            return [5 /*yield**/, _loop_1(iterator)];
                        case 2:
                            _b.sent();
                            _b.label = 3;
                        case 3:
                            _i++;
                            return [3 /*break*/, 1];
                        case 4:
                            if (!this.selectedPage) {
                                this.selectedPage = this.pages[0];
                            }
                            d = this.navigationService.registerNavigationHook(function (uri, _a) {
                                var target = _a.target;
                                if (target === _this.owner.tabChannelName ||
                                    (uri.protocol === "tab:" && uri.host === _this.owner.tabChannelName)) {
                                    return _this.loadPageForReturn(uri);
                                }
                            });
                            this.registerDisposable(d);
                            return [2 /*return*/];
                    }
                });
            });
        };
        AtomTabViewModel.prototype.watchSelectedPage = function () {
            this.saveState(this.selectedPage);
        };
        AtomTabViewModel.prototype.closePage = function (page) {
            var _this = this;
            this.app.runAsync(function () { return _this.navigationService.remove(page); });
        };
        AtomTabViewModel.prototype.saveState = function (a) {
            var state = {
                urls: this.pages.map(function (p) { return p.tag; }),
                selectedUrl: this.selectedUrl,
            };
            sessionStorage.setItem(this.storageKey, JSON.stringify(state));
        };
        AtomTabViewModel.prototype.loadPageForReturn = function (url) {
            return __awaiter(this, void 0, void 0, function () {
                var p, ex_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.loadPage(url, false)];
                        case 1:
                            p = _a.sent();
                            _a.label = 2;
                        case 2:
                            _a.trys.push([2, 4, , 5]);
                            return [4 /*yield*/, p.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 ex_1;
                        case 5: return [2 /*return*/];
                    }
                });
            });
        };
        AtomTabViewModel.prototype.loadPage = function (url, doNotSetSelected) {
            return __awaiter(this, void 0, void 0, function () {
                var uriString, existing, _a, page, disposables, e;
                var _this = this;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            uriString = url.toString();
                            existing = this.pages.find(function (x) { return x.tag === uriString; });
                            if (existing) {
                                if (!doNotSetSelected) {
                                    if (this.selectedPage !== existing) {
                                        this.selectedPage = existing;
                                    }
                                }
                                return [2 /*return*/, existing];
                            }
                            return [4 /*yield*/, AtomLoader_1.AtomLoader.loadView(url, this.app, true, function () { return new AtomWindowViewModel_1.AtomWindowViewModel(_this.app); })];
                        case 1:
                            _a = _b.sent(), page = _a.view, disposables = _a.disposables;
                            page.title = "Title";
                            page.tag = uriString;
                            if (url.query && url.query.title) {
                                page.title = url.query.title.toString();
                            }
                            page.bind(page.element, "title", [["viewModel", "title"]]);
                            page.bind(page.element, "styleDisplay", [["this", "selectedPage"]], false, function (v) { return v === page ? "" : "none"; }, this);
                            this.pages.add(page);
                            if (!doNotSetSelected) {
                                this.selectedPage = page;
                            }
                            e = page.element;
                            disposables.add(function () {
                                var index = _this.pages.indexOf(page);
                                if (_this.pages.length <= 1 && index <= 0) {
                                    return;
                                }
                                _this.pages.remove(page);
                                var pe = e.parentElement;
                                if (pe) {
                                    pe.remove();
                                }
                                e.innerHTML = "";
                                e.remove();
                                if (_this.selectedPage === page) {
                                    _this.selectedPage = _this.pages[index - 1];
                                }
                            });
                            disposables.add(page);
                            this.saveState();
                            return [2 /*return*/, page];
                    }
                });
            });
        };
        __decorate([
            BindableProperty_1.BindableProperty,
            __metadata("design:type", AtomList_1.AtomList)
        ], AtomTabViewModel.prototype, "pages", void 0);
        __decorate([
            BindableProperty_1.BindableProperty,
            __metadata("design:type", AtomPage_1.AtomPage)
        ], AtomTabViewModel.prototype, "selectedPage", void 0);
        __decorate([
            BindableProperty_1.BindableProperty,
            __metadata("design:type", String)
        ], AtomTabViewModel.prototype, "selectedUrl", void 0);
        __decorate([
            BindableProperty_1.BindableProperty,
            __metadata("design:type", Object)
        ], AtomTabViewModel.prototype, "tabState", void 0);
        __decorate([
            Inject_1.Inject,
            __metadata("design:type", NavigationService_1.NavigationService)
        ], AtomTabViewModel.prototype, "navigationService", void 0);
        __decorate([
            AtomViewModel_1.Watch,
            __metadata("design:type", Function),
            __metadata("design:paramtypes", []),
            __metadata("design:returntype", void 0)
        ], AtomTabViewModel.prototype, "watchSelectedPage", null);
        AtomTabViewModel = __decorate([
            __param(0, Inject_1.Inject),
            __metadata("design:paramtypes", [App_1.App, AtomTabbedPage])
        ], AtomTabViewModel);
        return AtomTabViewModel;
    }(AtomViewModel_1.AtomViewModel));
});
//# sourceMappingURL=AtomTabbedPage.js.map