import { EventEmitter, ReflectiveInjector } from '@angular/core';
import { convertToView, convertToViews, DIRECTION_BACK, DIRECTION_FORWARD, INIT_ZINDEX, ViewState } from './nav-util';
import { setZIndex } from './nav-util';
import { isBlank, isNumber, isPresent, removeArrayItem } from '../util/util';
import { isViewController, ViewController } from './view-controller';
import { Ion } from '../components/ion';
import { NavController } from './nav-controller';
import { NavParams } from './nav-params';
import { SwipeBackGesture } from './swipe-back';
export class NavControllerBase extends Ion {
    constructor(parent, _app, config, _keyboard, elementRef, _zone, renderer, _cfr, _gestureCtrl, _trnsCtrl, _linker, _domCtrl) {
        super(config, elementRef, renderer);
        this.parent = parent;
        this._app = _app;
        this.config = config;
        this._keyboard = _keyboard;
        this._zone = _zone;
        this._cfr = _cfr;
        this._gestureCtrl = _gestureCtrl;
        this._trnsCtrl = _trnsCtrl;
        this._linker = _linker;
        this._domCtrl = _domCtrl;
        this._children = [];
        this._ids = -1;
        this._init = false;
        this._queue = [];
        this._trnsId = null;
        this._trnsTm = false;
        this._views = [];
        this._zIndexOffset = 0;
        this.viewDidLoad = new EventEmitter();
        this.viewWillEnter = new EventEmitter();
        this.viewDidEnter = new EventEmitter();
        this.viewWillLeave = new EventEmitter();
        this.viewDidLeave = new EventEmitter();
        this.viewWillUnload = new EventEmitter();
        this._sbEnabled = config.getBoolean('swipeBackEnabled');
        this.id = 'n' + (++ctrlIds);
    }
    push(page, params, opts, done) {
        return this._queueTrns({
            insertStart: -1,
            insertViews: [convertToView(this._linker, page, params)],
            opts: opts,
        }, done);
    }
    insert(insertIndex, page, params, opts, done) {
        return this._queueTrns({
            insertStart: insertIndex,
            insertViews: [convertToView(this._linker, page, params)],
            opts: opts,
        }, done);
    }
    insertPages(insertIndex, insertPages, opts, done) {
        return this._queueTrns({
            insertStart: insertIndex,
            insertViews: convertToViews(this._linker, insertPages),
            opts: opts,
        }, done);
    }
    pop(opts, done) {
        return this._queueTrns({
            removeStart: -1,
            removeCount: 1,
            opts: opts,
        }, done);
    }
    popTo(indexOrViewCtrl, opts, done) {
        let config = {
            removeStart: -1,
            removeCount: -1,
            opts: opts
        };
        if (isViewController(indexOrViewCtrl)) {
            config.removeView = indexOrViewCtrl;
            config.removeStart = 1;
        }
        else if (isNumber(indexOrViewCtrl)) {
            config.removeStart = indexOrViewCtrl + 1;
        }
        return this._queueTrns(config, done);
    }
    popToRoot(opts, done) {
        return this._queueTrns({
            removeStart: 1,
            removeCount: -1,
            opts: opts,
        }, done);
    }
    popAll() {
        let promises = [];
        for (var i = this._views.length - 1; i >= 0; i--) {
            promises.push(this.pop(null));
        }
        return Promise.all(promises);
    }
    remove(startIndex, removeCount = 1, opts, done) {
        return this._queueTrns({
            removeStart: startIndex,
            removeCount: removeCount,
            opts: opts,
        }, done);
    }
    removeView(viewController, opts, done) {
        return this._queueTrns({
            removeView: viewController,
            removeStart: 0,
            removeCount: 1,
            opts: opts,
        }, done);
    }
    setRoot(pageOrViewCtrl, params, opts, done) {
        const viewControllers = [convertToView(this._linker, pageOrViewCtrl, params)];
        return this._setPages(viewControllers, opts, done);
    }
    setPages(pages, opts, done) {
        const viewControllers = convertToViews(this._linker, pages);
        return this._setPages(viewControllers, opts, done);
    }
    _setPages(viewControllers, opts, done) {
        if (isBlank(opts)) {
            opts = {};
        }
        if (opts.animate !== true) {
            opts.animate = false;
        }
        return this._queueTrns({
            insertStart: 0,
            insertViews: viewControllers,
            removeStart: 0,
            removeCount: -1,
            opts: opts
        }, done);
    }
    _queueTrns(ti, done) {
        let promise;
        let resolve = done;
        let reject = done;
        if (done === undefined) {
            promise = new Promise((res, rej) => {
                resolve = res;
                reject = rej;
            });
        }
        ti.resolve = (hasCompleted, isAsync, enteringName, leavingName, direction) => {
            this._trnsId = null;
            this._init = true;
            resolve && resolve(hasCompleted, isAsync, enteringName, leavingName, direction);
            this.setTransitioning(false);
            this._swipeBackCheck();
            this._nextTrns();
        };
        ti.reject = (rejectReason, trns) => {
            this._trnsId = null;
            this._queue.length = 0;
            while (trns) {
                if (trns.enteringView && (trns.enteringView._state !== ViewState.LOADED)) {
                    this._destroyView(trns.enteringView);
                }
                if (!trns.parent) {
                    break;
                }
            }
            if (trns) {
                this._trnsCtrl.destroy(trns.trnsId);
            }
            reject && reject(false, false, rejectReason);
            this.setTransitioning(false);
            this._swipeBackCheck();
            this._nextTrns();
        };
        if (ti.insertViews) {
            ti.insertViews = ti.insertViews.filter(v => v !== null);
            if (ti.insertViews.length === 0) {
                ti.reject('invalid views to insert');
                return promise;
            }
        }
        else if (isPresent(ti.removeStart) && this._views.length === 0 && !this._isPortal) {
            ti.reject('no views in the stack to be removed');
            return promise;
        }
        this._queue.push(ti);
        this._nextTrns();
        return promise;
    }
    _nextTrns() {
        if (this.isTransitioning()) {
            return false;
        }
        const ti = this._nextTI();
        if (!ti) {
            return false;
        }
        const leavingView = this.getActive();
        const enteringView = this._getEnteringView(ti, leavingView);
        if (!leavingView && !enteringView) {
            ti.reject('leavingView and enteringView are null. stack is already empty');
            return false;
        }
        this.setTransitioning(true);
        if (enteringView && isBlank(enteringView._state)) {
            this._viewInit(enteringView);
        }
        const requiresTransition = (ti.enteringRequiresTransition || ti.leavingRequiresTransition) && enteringView !== leavingView;
        if (requiresTransition) {
            return this._viewTest(enteringView, leavingView, ti);
        }
        else {
            return this._postViewInit(enteringView, leavingView, ti);
        }
    }
    _nextTI() {
        const ti = this._queue.shift();
        if (!ti) {
            return null;
        }
        const viewsLength = this._views.length;
        if (isPresent(ti.removeView)) {
            (void 0);
            (void 0);
            var index = this._views.indexOf(ti.removeView);
            if (index >= 0) {
                ti.removeStart += index;
            }
        }
        if (isPresent(ti.removeStart)) {
            if (ti.removeStart < 0) {
                ti.removeStart = (viewsLength - 1);
            }
            if (ti.removeCount < 0) {
                ti.removeCount = (viewsLength - ti.removeStart);
            }
            ti.leavingRequiresTransition = ((ti.removeStart + ti.removeCount) === viewsLength);
        }
        if (ti.insertViews) {
            if (ti.insertStart < 0 || ti.insertStart > viewsLength) {
                ti.insertStart = viewsLength;
            }
            ti.enteringRequiresTransition = (ti.insertStart === viewsLength);
        }
        return ti;
    }
    _getEnteringView(ti, leavingView) {
        const insertViews = ti.insertViews;
        if (insertViews) {
            return insertViews[insertViews.length - 1];
        }
        const removeStart = ti.removeStart;
        if (isPresent(removeStart)) {
            var views = this._views;
            var removeEnd = removeStart + ti.removeCount;
            var i;
            var view;
            for (i = views.length - 1; i >= 0; i--) {
                view = views[i];
                if ((i < removeStart || i >= removeEnd) && view !== leavingView) {
                    return view;
                }
            }
        }
        return null;
    }
    _postViewInit(enteringView, leavingView, ti) {
        (void 0);
        (void 0);
        (void 0);
        const opts = ti.opts || {};
        const insertViews = ti.insertViews;
        const removeStart = ti.removeStart;
        const removeCount = ti.removeCount;
        let view;
        let i;
        let destroyQueue;
        if (isPresent(removeStart)) {
            (void 0);
            (void 0);
            destroyQueue = [];
            for (i = 0; i < removeCount; i++) {
                view = this._views[i + removeStart];
                if (view && view !== enteringView && view !== leavingView) {
                    destroyQueue.push(view);
                }
            }
            opts.direction = opts.direction || DIRECTION_BACK;
        }
        const finalBalance = this._views.length + (insertViews ? insertViews.length : 0) - (removeCount ? removeCount : 0);
        (void 0);
        if (finalBalance === 0 && !this._isPortal) {
            console.warn(`You can't remove all the pages in the navigation stack. nav.pop() is probably called too many times.`, this, this.getNativeElement());
            ti.reject('navigation stack needs at least one root page');
            return false;
        }
        if (insertViews) {
            if (isPresent(opts.id)) {
                enteringView.id = opts.id;
            }
            for (i = 0; i < insertViews.length; i++) {
                view = insertViews[i];
                (void 0);
                this._insertViewAt(view, ti.insertStart + i);
            }
            if (ti.enteringRequiresTransition) {
                opts.direction = opts.direction || DIRECTION_FORWARD;
            }
        }
        if (destroyQueue && destroyQueue.length > 0) {
            this._zone.run(() => {
                for (i = 0; i < destroyQueue.length; i++) {
                    view = destroyQueue[i];
                    this._willLeave(view, true);
                    this._didLeave(view);
                    this._willUnload(view);
                }
            });
            for (i = 0; i < destroyQueue.length; i++) {
                this._destroyView(destroyQueue[i]);
            }
        }
        if (ti.enteringRequiresTransition || ti.leavingRequiresTransition && enteringView !== leavingView) {
            if (!opts.animation) {
                if (isPresent(ti.removeStart)) {
                    opts.animation = (leavingView || enteringView).getTransitionName(opts.direction);
                }
                else {
                    opts.animation = (enteringView || leavingView).getTransitionName(opts.direction);
                }
            }
            this._transition(enteringView, leavingView, opts, ti.resolve);
        }
        else {
            ti.resolve(true, false);
        }
        return true;
    }
    _viewInit(enteringView) {
        const componentProviders = ReflectiveInjector.resolve([
            { provide: NavController, useValue: this },
            { provide: ViewController, useValue: enteringView },
            { provide: NavParams, useValue: enteringView.getNavParams() }
        ]);
        const componentFactory = this._cfr.resolveComponentFactory(enteringView.component);
        const childInjector = ReflectiveInjector.fromResolvedProviders(componentProviders, this._viewport.parentInjector);
        enteringView.init(componentFactory.create(childInjector, []));
        enteringView._state = ViewState.INITIALIZED;
        this._preLoad(enteringView);
    }
    _viewAttachToDOM(view, componentRef, viewport) {
        (void 0);
        this._willLoad(view);
        viewport.insert(componentRef.hostView, viewport.length);
        view._state = ViewState.PRE_RENDERED;
        if (view._cssClass) {
            var pageElement = componentRef.location.nativeElement;
            this._renderer.setElementClass(pageElement, view._cssClass, true);
        }
        componentRef.changeDetectorRef.detectChanges();
        this._zone.run(this._didLoad.bind(this, view));
    }
    _viewTest(enteringView, leavingView, ti) {
        const promises = [];
        if (leavingView) {
            var leavingTestResult = leavingView._lifecycleTest('Leave');
            if (leavingTestResult === false) {
                ti.reject((leavingTestResult !== false ? leavingTestResult : `ionViewCanLeave rejected`));
                return false;
            }
            else if (leavingTestResult instanceof Promise) {
                promises.push(leavingTestResult);
            }
        }
        if (enteringView) {
            var enteringTestResult = enteringView._lifecycleTest('Enter');
            if (enteringTestResult === false) {
                ti.reject((enteringTestResult !== false ? enteringTestResult : `ionViewCanEnter rejected`));
                return false;
            }
            else if (enteringTestResult instanceof Promise) {
                promises.push(enteringTestResult);
            }
        }
        if (promises.length) {
            Promise.all(promises).then((values) => {
                if (values.some(result => result === false)) {
                    ti.reject(`ionViewCanEnter rejected`);
                }
                else {
                    this._postViewInit(enteringView, leavingView, ti);
                }
            }).catch(ti.reject);
            return true;
        }
        else {
            return this._postViewInit(enteringView, leavingView, ti);
        }
    }
    _transition(enteringView, leavingView, opts, resolve) {
        this._trnsId = this._trnsCtrl.getRootTrnsId(this);
        if (this._trnsId === null) {
            this._trnsId = this._trnsCtrl.nextId();
        }
        const animationOpts = {
            animation: opts.animation,
            direction: opts.direction,
            duration: (opts.animate === false ? 0 : opts.duration),
            easing: opts.easing,
            isRTL: this._config.platform.isRTL(),
            ev: opts.ev,
        };
        const transition = this._trnsCtrl.get(this._trnsId, enteringView, leavingView, animationOpts);
        this._sbTrns && this._sbTrns.destroy();
        this._sbTrns = null;
        if (transition.isRoot() && opts.progressAnimation) {
            this._sbTrns = transition;
        }
        transition.registerStart(() => {
            this._trnsStart(transition, enteringView, leavingView, opts, resolve);
            if (transition.parent) {
                transition.parent.start();
            }
        });
        if (enteringView && enteringView._state === ViewState.INITIALIZED) {
            this._viewAttachToDOM(enteringView, enteringView._cmp, this._viewport);
        }
        else {
            (void 0);
        }
        if (!transition.hasChildren) {
            transition.start();
        }
    }
    _trnsStart(transition, enteringView, leavingView, opts, resolve) {
        (void 0);
        this._trnsId = null;
        setZIndex(this, enteringView, leavingView, opts.direction, this._renderer);
        enteringView && enteringView._domShow(true, this._renderer);
        leavingView && leavingView._domShow(true, this._renderer);
        transition.init();
        const isFirstPage = !this._init && this._views.length === 1;
        const shouldNotAnimate = isFirstPage && !this._isPortal;
        const canNotAnimate = this._config.get('animate') === false;
        if (shouldNotAnimate || canNotAnimate) {
            opts.animate = false;
        }
        if (opts.animate === false) {
            transition.duration(0);
        }
        transition.beforeAddRead(this._viewsWillLifecycles.bind(this, enteringView, leavingView));
        transition.onFinish(() => {
            this._zone.run(this._trnsFinish.bind(this, transition, opts, resolve));
        });
        const duration = transition.getDuration();
        if (transition.isRoot()) {
            if (duration > DISABLE_APP_MINIMUM_DURATION && opts.disableApp !== false) {
                this._app.setEnabled(false, duration + ACTIVE_TRANSITION_OFFSET);
            }
            else {
                (void 0);
            }
            if (opts.progressAnimation) {
                transition.progressStart();
            }
            else {
                transition.play();
            }
        }
    }
    _viewsWillLifecycles(enteringView, leavingView) {
        if (enteringView || leavingView) {
            this._zone.run(() => {
                leavingView && this._willLeave(leavingView, !enteringView);
                enteringView && this._willEnter(enteringView);
            });
        }
    }
    _trnsFinish(transition, opts, resolve) {
        const hasCompleted = transition.hasCompleted;
        const enteringView = transition.enteringView;
        const leavingView = transition.leavingView;
        let enteringName;
        let leavingName;
        if (hasCompleted) {
            if (enteringView) {
                enteringName = enteringView.name;
                this._didEnter(enteringView);
            }
            if (leavingView) {
                leavingName = leavingView.name;
                this._didLeave(leavingView);
            }
            this._cleanup(enteringView);
        }
        else {
            this._cleanup(leavingView);
        }
        if (transition.isRoot()) {
            this._trnsCtrl.destroy(transition.trnsId);
            this._app.setEnabled(true);
            if (opts.updateUrl !== false) {
                this._linker.navChange(opts.direction);
            }
            if (opts.keyboardClose !== false) {
                this._keyboard.close();
            }
        }
        resolve(hasCompleted, true, enteringName, leavingName, opts.direction);
    }
    _insertViewAt(view, index) {
        const existingIndex = this._views.indexOf(view);
        if (existingIndex > -1) {
            this._views.splice(index, 0, this._views.splice(existingIndex, 1)[0]);
        }
        else {
            view._setNav(this);
            this._ids++;
            if (!view.id) {
                view.id = `${this.id}-${this._ids}`;
            }
            this._views.splice(index, 0, view);
        }
    }
    _removeView(view) {
        const views = this._views;
        const index = views.indexOf(view);
        (void 0);
        if (index >= 0) {
            views.splice(index, 1);
        }
    }
    _destroyView(view) {
        view._destroy(this._renderer);
        this._removeView(view);
    }
    _cleanup(activeView) {
        const activeViewIndex = this.indexOf(activeView);
        const views = this._views;
        let reorderZIndexes = false;
        let view;
        let i;
        for (i = views.length - 1; i >= 0; i--) {
            view = views[i];
            if (i > activeViewIndex) {
                this._willUnload(view);
                this._destroyView(view);
            }
            else if (i < activeViewIndex && !this._isPortal) {
                view._domShow(false, this._renderer);
            }
            if (view._zIndex <= 0) {
                reorderZIndexes = true;
            }
        }
        if (!this._isPortal && reorderZIndexes) {
            for (i = 0; i < views.length; i++) {
                view = views[i];
                view._setZIndex(view._zIndex + INIT_ZINDEX + 1, this._renderer);
            }
        }
    }
    _preLoad(view) {
        (void 0);
        view._preLoad();
    }
    _willLoad(view) {
        (void 0);
        view._willLoad();
    }
    _didLoad(view) {
        (void 0);
        (void 0);
        view._didLoad();
        this.viewDidLoad.emit(view);
        this._app.viewDidLoad.emit(view);
    }
    _willEnter(view) {
        (void 0);
        (void 0);
        view._willEnter();
        this.viewWillEnter.emit(view);
        this._app.viewWillEnter.emit(view);
    }
    _didEnter(view) {
        (void 0);
        (void 0);
        view._didEnter();
        this.viewDidEnter.emit(view);
        this._app.viewDidEnter.emit(view);
    }
    _willLeave(view, willUnload) {
        (void 0);
        (void 0);
        view._willLeave(willUnload);
        this.viewWillLeave.emit(view);
        this._app.viewWillLeave.emit(view);
    }
    _didLeave(view) {
        (void 0);
        (void 0);
        view._didLeave();
        this.viewDidLeave.emit(view);
        this._app.viewDidLeave.emit(view);
    }
    _willUnload(view) {
        (void 0);
        (void 0);
        view._willUnload();
        this.viewWillUnload.emit(view);
        this._app.viewWillUnload.emit(view);
    }
    getActiveChildNav() {
        return this._children[this._children.length - 1];
    }
    registerChildNav(nav) {
        this._children.push(nav);
    }
    unregisterChildNav(nav) {
        removeArrayItem(this._children, nav);
    }
    destroy() {
        const views = this._views;
        let view;
        for (var i = 0; i < views.length; i++) {
            view = views[i];
            view._willUnload();
            view._destroy(this._renderer);
        }
        this._views.length = 0;
        this._sbGesture && this._sbGesture.destroy();
        this._sbTrns && this._sbTrns.destroy();
        this._sbGesture = this._sbTrns = null;
        if (this.parent && this.parent.unregisterChildNav) {
            this.parent.unregisterChildNav(this);
        }
    }
    swipeBackStart() {
        if (this.isTransitioning() || this._queue.length > 0) {
            return;
        }
        const opts = {
            direction: DIRECTION_BACK,
            progressAnimation: true
        };
        this._queueTrns({
            removeStart: -1,
            removeCount: 1,
            opts: opts,
        }, null);
    }
    swipeBackProgress(stepValue) {
        if (this._sbTrns && this._sbGesture) {
            this._app.setEnabled(false, ACTIVE_TRANSITION_DEFAULT);
            this.setTransitioning(true);
            this._sbTrns.progressStep(stepValue);
        }
    }
    swipeBackEnd(shouldComplete, currentStepValue, velocity) {
        if (this._sbTrns && this._sbGesture) {
            var dur = this._sbTrns.getDuration() / (Math.abs(velocity) + 1);
            this._sbTrns.progressEnd(shouldComplete, currentStepValue, dur);
        }
    }
    _swipeBackCheck() {
        if (this.canSwipeBack()) {
            if (!this._sbGesture) {
                this._sbGesture = new SwipeBackGesture(this, this._gestureCtrl, this._domCtrl);
            }
            this._sbGesture.listen();
        }
        else if (this._sbGesture) {
            this._sbGesture.unlisten();
        }
    }
    canSwipeBack() {
        return (this._sbEnabled &&
            !this._isPortal &&
            !this._children.length &&
            !this.isTransitioning() &&
            this._app.isEnabled() &&
            this.canGoBack());
    }
    canGoBack() {
        const activeView = this.getActive();
        return !!(activeView && activeView.enableBack());
    }
    isTransitioning() {
        return this._trnsTm;
    }
    setTransitioning(isTransitioning) {
        this._trnsTm = isTransitioning;
    }
    getActive() {
        return this._views[this._views.length - 1];
    }
    isActive(view) {
        return (view === this.getActive());
    }
    getByIndex(index) {
        return this._views[index];
    }
    getPrevious(view) {
        if (!view) {
            view = this.getActive();
        }
        return this._views[this.indexOf(view) - 1];
    }
    first() {
        return this._views[0];
    }
    last() {
        return this._views[this._views.length - 1];
    }
    indexOf(view) {
        return this._views.indexOf(view);
    }
    length() {
        return this._views.length;
    }
    getViews() {
        return this._views;
    }
    isSwipeBackEnabled() {
        return this._sbEnabled;
    }
    dismissPageChangeViews() {
        for (let view of this._views) {
            if (view.data && view.data.dismissOnPageChange) {
                view.dismiss();
            }
        }
    }
    setViewport(val) {
        this._viewport = val;
    }
}
let ctrlIds = -1;
const DISABLE_APP_MINIMUM_DURATION = 64;
const ACTIVE_TRANSITION_DEFAULT = 5000;
const ACTIVE_TRANSITION_OFFSET = 2000;
//# sourceMappingURL=nav-controller-base.js.map