/**
 * DevExtreme (ui/scroll_view/ui.scrollable.native.js)
 * Version: 16.2.5
 * Build date: Mon Feb 27 2017
 *
 * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
 * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
 */
"use strict";
var $ = require("jquery"),
    devices = require("../../core/devices"),
    Class = require("../../core/class"),
    Scrollbar = require("./ui.scrollbar");
var SCROLLABLE_NATIVE = "dxNativeScrollable",
    SCROLLABLE_NATIVE_CLASS = "dx-scrollable-native",
    SCROLLABLE_SCROLLBAR_SIMULATED = "dx-scrollable-scrollbar-simulated",
    SCROLLABLE_SCROLLBARS_HIDDEN = "dx-scrollable-scrollbars-hidden",
    VERTICAL = "vertical",
    HORIZONTAL = "horizontal",
    HIDE_SCROLLBAR_TIMEOUT = 500;
var NativeStrategy = Class.inherit({
    ctor: function(scrollable) {
        this._init(scrollable)
    },
    _init: function(scrollable) {
        this._component = scrollable;
        this._$element = scrollable.element();
        this._$container = scrollable._$container;
        this._$content = scrollable._$content;
        this._direction = scrollable.option("direction");
        this._useSimulatedScrollbar = scrollable.option("useSimulatedScrollbar");
        this._showScrollbar = scrollable.option("showScrollbar");
        this.option = $.proxy(scrollable.option, scrollable);
        this._createActionByOption = $.proxy(scrollable._createActionByOption, scrollable);
        this._isLocked = $.proxy(scrollable._isLocked, scrollable);
        this._isDirection = $.proxy(scrollable._isDirection, scrollable);
        this._allowedDirection = $.proxy(scrollable._allowedDirection, scrollable)
    },
    render: function() {
        this._renderPushBackOffset();
        var device = devices.real(),
            deviceType = device.platform;
        this._$element.addClass(SCROLLABLE_NATIVE_CLASS).addClass(SCROLLABLE_NATIVE_CLASS + "-" + deviceType).toggleClass(SCROLLABLE_SCROLLBARS_HIDDEN, !this._showScrollbar);
        if (this._showScrollbar && this._useSimulatedScrollbar) {
            this._renderScrollbars()
        }
    },
    _renderPushBackOffset: function() {
        var pushBackValue = this.option("pushBackValue");
        if (!pushBackValue && !this._component._lastPushBackValue) {
            return
        }
        this._$content.css({
            paddingTop: pushBackValue,
            paddingBottom: pushBackValue
        });
        this._component._lastPushBackValue = pushBackValue
    },
    _renderScrollbars: function() {
        this._scrollbars = {};
        this._hideScrollbarTimeout = 0;
        this._$element.addClass(SCROLLABLE_SCROLLBAR_SIMULATED);
        this._renderScrollbar(VERTICAL);
        this._renderScrollbar(HORIZONTAL)
    },
    _renderScrollbar: function(direction) {
        if (!this._isDirection(direction)) {
            return
        }
        this._scrollbars[direction] = new Scrollbar($("<div>").appendTo(this._$element), {
            direction: direction,
            expandable: this._component.option("scrollByThumb")
        })
    },
    handleInit: $.noop,
    handleStart: function() {
        this._disablePushBack = true
    },
    handleMove: function(e) {
        if (this._isLocked()) {
            e.cancel = true;
            return
        }
        if (this._allowedDirection()) {
            e.originalEvent.isScrollingEvent = true
        }
    },
    handleEnd: function() {
        this._disablePushBack = false
    },
    handleStop: $.noop,
    _eachScrollbar: function(callback) {
        callback = $.proxy(callback, this);
        $.each(this._scrollbars || {}, function(direction, scrollbar) {
            callback(scrollbar, direction)
        })
    },
    createActions: function() {
        this._scrollAction = this._createActionByOption("onScroll");
        this._updateAction = this._createActionByOption("onUpdated")
    },
    _createActionArgs: function() {
        var location = this.location();
        return {
            jQueryEvent: this._eventForUserAction,
            scrollOffset: {
                top: -location.top,
                left: -location.left
            },
            reachedLeft: this._isDirection(HORIZONTAL) ? location.left >= 0 : void 0,
            reachedRight: this._isDirection(HORIZONTAL) ? location.left <= this._containerSize.width - this._componentContentSize.width : void 0,
            reachedTop: this._isDirection(VERTICAL) ? location.top >= 0 : void 0,
            reachedBottom: this._isDirection(VERTICAL) ? location.top <= this._containerSize.height - this._componentContentSize.height : void 0
        }
    },
    handleScroll: function(e) {
        if (!this._isScrollLocationChanged()) {
            e.stopImmediatePropagation();
            return
        }
        this._eventForUserAction = e;
        this._moveScrollbars();
        this._scrollAction(this._createActionArgs());
        this._lastLocation = this.location();
        this._pushBackFromBoundary()
    },
    _pushBackFromBoundary: function() {
        var pushBackValue = this.option("pushBackValue");
        if (!pushBackValue || this._disablePushBack) {
            return
        }
        var scrollOffset = this._containerSize.height - this._contentSize.height,
            scrollTopPos = this._$container.scrollTop(),
            scrollBottomPos = scrollOffset + scrollTopPos - 2 * pushBackValue;
        if (!scrollTopPos) {
            this._$container.scrollTop(pushBackValue)
        } else {
            if (!scrollBottomPos) {
                this._$container.scrollTop(pushBackValue - scrollOffset)
            }
        }
    },
    _isScrollLocationChanged: function() {
        var currentLocation = this.location(),
            lastLocation = this._lastLocation || {},
            isTopChanged = lastLocation.top !== currentLocation.top,
            isLeftChanged = lastLocation.left !== currentLocation.left;
        return isTopChanged || isLeftChanged
    },
    _moveScrollbars: function() {
        this._eachScrollbar(function(scrollbar) {
            scrollbar.moveTo(this.location());
            scrollbar.option("visible", true)
        });
        this._hideScrollbars()
    },
    _hideScrollbars: function() {
        clearTimeout(this._hideScrollbarTimeout);
        this._hideScrollbarTimeout = setTimeout($.proxy(function() {
            this._eachScrollbar(function(scrollbar) {
                scrollbar.option("visible", false)
            })
        }, this), HIDE_SCROLLBAR_TIMEOUT)
    },
    location: function() {
        return {
            left: -this._$container.scrollLeft(),
            top: this.option("pushBackValue") - this._$container.scrollTop()
        }
    },
    disabledChanged: $.noop,
    update: function() {
        this._update();
        this._updateAction(this._createActionArgs())
    },
    _update: function() {
        this._updateDimensions();
        this._updateScrollbars()
    },
    _updateDimensions: function() {
        this._containerSize = {
            height: this._$container.height(),
            width: this._$container.width()
        };
        this._componentContentSize = {
            height: this._component.content().height(),
            width: this._component.content().width()
        };
        this._contentSize = {
            height: this._$content.height(),
            width: this._$content.width()
        };
        this._pushBackFromBoundary()
    },
    _updateScrollbars: function() {
        this._eachScrollbar(function(scrollbar, direction) {
            var dimension = direction === VERTICAL ? "height" : "width";
            scrollbar.option({
                containerSize: this._containerSize[dimension],
                contentSize: this._componentContentSize[dimension]
            });
            scrollbar.update()
        })
    },
    _allowedDirections: function() {
        return {
            vertical: this._isDirection(VERTICAL) && this._contentSize.height > this._containerSize.height,
            horizontal: this._isDirection(HORIZONTAL) && this._contentSize.width > this._containerSize.width
        }
    },
    dispose: function() {
        this._$element.removeClass(function(index, className) {
            var scrollableNativeRegexp = new RegExp(SCROLLABLE_NATIVE_CLASS + "\\S*", "g");
            if (scrollableNativeRegexp.test(className)) {
                return className.match(scrollableNativeRegexp).join(" ")
            }
        });
        this._$element.off("." + SCROLLABLE_NATIVE);
        this._$container.off("." + SCROLLABLE_NATIVE);
        this._removeScrollbars();
        clearTimeout(this._gestureEndTimer);
        clearTimeout(this._hideScrollbarTimeout)
    },
    _removeScrollbars: function() {
        this._eachScrollbar(function(scrollbar) {
            scrollbar.element().remove()
        })
    },
    scrollBy: function(distance) {
        var location = this.location();
        this._$container.scrollTop(-location.top - distance.top + this.option("pushBackValue"));
        this._$container.scrollLeft(-location.left - distance.left)
    },
    validate: function() {
        return !this.option("disabled") && this._allowedDirection()
    },
    getDirection: function() {
        return this._allowedDirection()
    },
    verticalOffset: function() {
        return this.option("pushBackValue")
    }
});
module.exports = NativeStrategy;
