(function () {
    'use strict';
    angular.module('uniflash').directive('scrollPosition', ScrollPosition);
    ScrollPosition.$inject = ['$rootScope'];
    function ScrollPosition($rootScope) {
        return {
            scope: {
                rows: '=',
                topRow: '=',
                centerRow: '=',
                updateScrollInfo: '='
            },
            link: function (scope, ele, attrs) {
                var raw = document.getElementById('memory-browser');
                var element = angular.element(raw);
                var previousTopRow = scope.topRow;
                scope.offsetHeight = element[0].offsetHeight;
                function updateScrollVals() {
                    scope.scrollTop = element[0].scrollTop;
                    scope.scrollHeight = element[0].scrollHeight;
                    scope.rowHeight = element[0].scrollHeight / (scope.rows.length + 2);
                    var ret = {
                        scrollTop: scope.scrollTop,
                        scrollHeight: scope.scrollHeight,
                        rowHeight: scope.rowHeight
                    };
                    //console.log(JSON.stringify(ret));
                    return ret;
                }
                scope.updateScrollInfo(updateScrollVals());
                element.bind('scroll', function () {
                    scope.updateScrollInfo(updateScrollVals());
                });
                scope.$on('$destroy', function () {
                    element.unbind('scroll');
                });
                function updateScrollTop() {
                    updateScrollVals();
                    // this should be removed once the address area div are not part of the scroll bar
                    var directionOffset = (scope.topRow === 0) ? 0 : 2;
                    var newScrollTop = scope.rowHeight * Math.round(scope.centerRow - scope.topRow + directionOffset);
                    element[0].scrollTop = newScrollTop;
                    previousTopRow = scope.topRow;
                    // console.log('topRow = ' + scope.topRow + ' centerRow = ' + scope.centerRow + ' scrollTop = ' + element[0].scrollTop + ' directionOffset = ' + directionOffset);
                }
                scope.$watch('centerRow', updateScrollTop);
                scope.$on('$destroy', $rootScope.$on('memory_browser.afterMemoryLoad', updateScrollTop));
            }
        };
    }
})();
