import { Subject } from 'rxjs/Subject';
import { CSS, nativeRaf, pointerCoord, rafFrames } from './dom';
import { eventOptions, listenEvent } from './ui-event-manager';
export var ScrollView = (function () {
    function ScrollView(_dom) {
        this._dom = _dom;
        this.isScrolling = false;
        this.scrollStart = new Subject();
        this.scroll = new Subject();
        this.scrollEnd = new Subject();
        this._t = 0;
        this._l = 0;
        this.ev = {
            directionY: ScrollDirection.Down,
            directionX: null
        };
    }
    ScrollView.prototype.init = function (ele, contentTop, contentBottom) {
        if (!this._el) {
            (void 0);
            this._el = ele;
            if (this._js) {
                this.enableJsScroll(contentTop, contentBottom);
            }
            else {
                this.enableNativeScrolling();
            }
        }
    };
    ScrollView.prototype.enableNativeScrolling = function () {
        this._js = false;
        if (!this._el) {
            return;
        }
        (void 0);
        var self = this;
        var ev = self.ev;
        var positions = [];
        function scrollCallback(scrollEvent) {
            ev.timeStamp = scrollEvent.timeStamp;
            ev.scrollTop = self.getTop();
            ev.scrollLeft = self.getLeft();
            if (!self.isScrolling) {
                self.isScrolling = true;
                ev.startY = ev.scrollTop;
                ev.startX = ev.scrollLeft;
                ev.velocityY = ev.velocityX = 0;
                ev.deltaY = ev.deltaX = 0;
                positions.length = 0;
                self.scrollStart.next(ev);
            }
            positions.push(ev.scrollTop, ev.scrollLeft, ev.timeStamp);
            if (positions.length > 3) {
                ev.deltaY = (ev.scrollTop - ev.startY);
                ev.deltaX = (ev.scrollLeft - ev.startX);
                var endPos = (positions.length - 1);
                var startPos = endPos;
                var timeRange = (ev.timeStamp - 100);
                for (var i = endPos; i > 0 && positions[i] > timeRange; i -= 3) {
                    startPos = i;
                }
                if (startPos !== endPos) {
                    var timeOffset = (positions[endPos] - positions[startPos]);
                    var movedTop = (positions[startPos - 2] - positions[endPos - 2]);
                    var movedLeft = (positions[startPos - 1] - positions[endPos - 1]);
                    ev.velocityY = ((movedTop / timeOffset) * FRAME_MS);
                    ev.velocityX = ((movedLeft / timeOffset) * FRAME_MS);
                    ev.directionY = (movedTop > 0 ? ScrollDirection.Up : ScrollDirection.Down);
                    ev.directionX = (movedLeft > 0 ? ScrollDirection.Left : ScrollDirection.Right);
                }
            }
            self.scroll.next(ev);
            self._endTmr && self._endTmr();
            self._endTmr = rafFrames(5, function scrollEnd() {
                self.isScrolling = false;
                ev.velocityY = ev.velocityX = 0;
                self.scrollEnd.next(ev);
            });
        }
        ;
        self._lsn && self._lsn();
        var opts = eventOptions(false, false);
        self._lsn = listenEvent(self._el, 'scroll', false, opts, scrollCallback);
    };
    ScrollView.prototype.enableJsScroll = function (contentTop, contentBottom) {
        var self = this;
        self._js = true;
        var ele = self._el;
        if (!ele) {
            return;
        }
        (void 0);
        var positions = [];
        var rafCancel;
        var max;
        var ev = self.ev;
        ev.scrollLeft = 0;
        ev.startX = 0;
        ev.deltaX = 0;
        ev.velocityX = 0;
        ev.directionX = null;
        function setMax() {
            if (!max) {
                max = (ele.scrollHeight - ele.offsetHeight) + contentTop + contentBottom;
            }
        }
        ;
        function jsScrollDecelerate(timeStamp) {
            ev.timeStamp = timeStamp;
            (void 0);
            if (ev.velocityY) {
                ev.velocityY *= DECELERATION_FRICTION;
                setMax();
                self._t = Math.min(Math.max(self._t + ev.velocityY, 0), max);
                ev.scrollTop = self._t;
                self.scroll.next(ev);
                self._dom.write(function () {
                    self.setTop(self._t);
                    if (self._t > 0 && self._t < max && Math.abs(ev.velocityY) > MIN_VELOCITY_CONTINUE_DECELERATION) {
                        rafCancel = self._dom.read(function (rafTimeStamp) {
                            jsScrollDecelerate(rafTimeStamp);
                        });
                    }
                    else {
                        self.isScrolling = false;
                        ev.velocityY = ev.velocityX = 0;
                        self.scrollEnd.next(ev);
                    }
                });
            }
        }
        function jsScrollTouchStart(touchEvent) {
            positions.length = 0;
            max = null;
            positions.push(pointerCoord(touchEvent).y, touchEvent.timeStamp);
        }
        function jsScrollTouchMove(touchEvent) {
            if (!positions.length) {
                return;
            }
            ev.timeStamp = touchEvent.timeStamp;
            var y = pointerCoord(touchEvent).y;
            setMax();
            self._t -= (y - positions[positions.length - 2]);
            self._t = Math.min(Math.max(self._t, 0), max);
            positions.push(y, ev.timeStamp);
            if (!self.isScrolling) {
                ev.startY = self._t;
                ev.velocityY = ev.deltaY = 0;
                self.isScrolling = true;
                self.scrollStart.next(ev);
            }
            self._dom.write(function () {
                self.setTop(self._t);
            });
        }
        function jsScrollTouchEnd(touchEvent) {
            self._dom.cancel(rafCancel);
            if (!positions.length && self.isScrolling) {
                self.isScrolling = false;
                ev.velocityY = ev.velocityX = 0;
                self.scrollEnd.next(ev);
                return;
            }
            var y = pointerCoord(touchEvent).y;
            positions.push(y, touchEvent.timeStamp);
            var endPos = (positions.length - 1);
            var startPos = endPos;
            var timeRange = (touchEvent.timeStamp - 100);
            for (var i = endPos; i > 0 && positions[i] > timeRange; i -= 2) {
                startPos = i;
            }
            if (startPos !== endPos) {
                var timeOffset = (positions[endPos] - positions[startPos]);
                var movedTop = (positions[startPos - 1] - positions[endPos - 1]);
                ev.velocityY = ((movedTop / timeOffset) * FRAME_MS);
                if (Math.abs(ev.velocityY) > MIN_VELOCITY_START_DECELERATION) {
                    setMax();
                    rafCancel = self._dom.read(function (rafTimeStamp) {
                        jsScrollDecelerate(rafTimeStamp);
                    });
                }
            }
            else {
                self.isScrolling = false;
                ev.velocityY = ev.velocityX = 0;
                self.scrollEnd.next(ev);
            }
            positions.length = 0;
        }
        var opts = eventOptions(false, true);
        var unRegStart = listenEvent(ele, 'touchstart', false, opts, jsScrollTouchStart);
        var unRegMove = listenEvent(ele, 'touchmove', false, opts, jsScrollTouchMove);
        var unRegEnd = listenEvent(ele, 'touchend', false, opts, jsScrollTouchEnd);
        ele.parentElement.classList.add('js-scroll');
        self._lsn && self._lsn();
        self._lsn = function () {
            unRegStart();
            unRegMove();
            unRegEnd();
            ele.parentElement.classList.remove('js-scroll');
        };
    };
    ScrollView.prototype.getTop = function () {
        if (this._js) {
            return this._t;
        }
        return this._t = this._el.scrollTop || 0;
    };
    ScrollView.prototype.getLeft = function () {
        if (this._js) {
            return 0;
        }
        return this._l = this._el.scrollLeft || 0;
    };
    ScrollView.prototype.setTop = function (top) {
        this._t = top;
        if (this._js) {
            this._el.style[CSS.transform] = "translate3d(" + this._l * -1 + "px," + top * -1 + "px,0px)";
        }
        else {
            this._el.scrollTop = top;
        }
    };
    ScrollView.prototype.setLeft = function (left) {
        this._l = left;
        if (this._js) {
            this._el.style[CSS.transform] = "translate3d(" + left * -1 + "px," + this._t * -1 + "px,0px)";
        }
        else {
            this._el.scrollLeft = left;
        }
    };
    ScrollView.prototype.scrollTo = function (x, y, duration, done) {
        var promise;
        if (done === undefined) {
            promise = new Promise(function (resolve) {
                done = resolve;
            });
        }
        var self = this;
        if (!self._el) {
            done();
            return promise;
        }
        x = x || 0;
        y = y || 0;
        var fromY = self._el.scrollTop;
        var fromX = self._el.scrollLeft;
        var maxAttempts = (duration / 16) + 100;
        var startTime;
        var attempts = 0;
        function step(timeStamp) {
            attempts++;
            if (!self._el || !self.isScrolling || attempts > maxAttempts) {
                self.isScrolling = false;
                self._el.style.transform = "";
                done();
                return;
            }
            var time = Math.min(1, ((timeStamp - startTime) / duration));
            var easedT = (--time) * time * time + 1;
            if (fromY !== y) {
                self.setTop((easedT * (y - fromY)) + fromY);
            }
            if (fromX !== x) {
                self.setLeft(Math.floor((easedT * (x - fromX)) + fromX));
            }
            if (easedT < 1) {
                nativeRaf(step);
            }
            else {
                self.isScrolling = false;
                self._el.style.transform = "";
                done();
            }
        }
        self.isScrolling = true;
        rafFrames(2, function (timeStamp) {
            startTime = timeStamp;
            step(timeStamp);
        });
        return promise;
    };
    ScrollView.prototype.scrollToTop = function (duration) {
        return this.scrollTo(0, 0, duration);
    };
    ScrollView.prototype.scrollToBottom = function (duration) {
        var y = 0;
        if (this._el) {
            y = this._el.scrollHeight - this._el.clientHeight;
        }
        return this.scrollTo(0, y, duration);
    };
    ScrollView.prototype.stop = function () {
        this.isScrolling = false;
    };
    ScrollView.prototype.destroy = function () {
        this.scrollStart.unsubscribe();
        this.scroll.unsubscribe();
        this.scrollEnd.unsubscribe();
        this.stop();
        this._endTmr && this._endTmr();
        this._lsn && this._lsn();
        this._el = this._dom = null;
    };
    return ScrollView;
}());
export var ScrollDirection;
(function (ScrollDirection) {
    ScrollDirection[ScrollDirection["Up"] = 0] = "Up";
    ScrollDirection[ScrollDirection["Down"] = 1] = "Down";
    ScrollDirection[ScrollDirection["Left"] = 2] = "Left";
    ScrollDirection[ScrollDirection["Right"] = 3] = "Right";
})(ScrollDirection || (ScrollDirection = {}));
var MIN_VELOCITY_START_DECELERATION = 4;
var MIN_VELOCITY_CONTINUE_DECELERATION = 0.12;
var DECELERATION_FRICTION = 0.97;
var FRAME_MS = (1000 / 60);
//# sourceMappingURL=scroll-view.js.map