var angular = require('angular');
require('../modules');
require('../../../commons/services/Timer');
require('ngIonic');

var module = angular.module('linker.directives.linkernav'),
  STATE_LINKER_NAV_SCROLL = 1,
  STATE_CONTENT_SCROLL = 2;

/**
 * 产生联系人导航项
 * @return {Array}
 */
function generateLinkerNavs() {
  var linkerNavs = [{id: '搜', text: '', classes: 'icon ion-ios-search'}];
  for (var i = 0; i < 26; i++) {
    var letter = String.fromCharCode(65 + i);
    linkerNavs.push({id: letter, text: letter});
  }

  return linkerNavs;
}

module.directive('linkerNav', function($ionicScrollDelegate, Timer, $timeout) {
  return {
    restrict: 'E',
    templateUrl: 'views/linker/directives/linkerNav.tpl.html',
    replace: true,
    scope: {
      itemConfig: '=',
      letterBeginPosition: '@',
      scrollviewName: '@',
      itemHeight: '@'
    },
    link: function(scope, element) {
      var height = element[0].scrollHeight,
        top = element[0].offsetTop,
        state = STATE_CONTENT_SCROLL,
        fixedHeight = parseInt(scope.letterBeginPosition),
        itemHeight = parseFloat(scope.itemHeight),
        scrollView = $ionicScrollDelegate.$getByHandle(scope.scrollviewName),
        currentItemIndex = -1,
        usefulLinkerNav = null;
      scope.linkerNavs = generateLinkerNavs();
      scope.selectedNav = scope.linkerNavs[0].id;
      scope.start = 0;

      function getLinkerNavByContentScrollPosition() {
        var top = scrollView.getScrollPosition().top,
          _top = top - fixedHeight,
          linkerNav = null;

        if (_top <= 0) {
          linkerNav = '搜';
        } else {
          var position = getItemIndexByContentScrollPosition();
          linkerNav = scope.itemConfig.getLinkerNavFn(position);
        }

        return linkerNav;
      }


      function getItemIndexByContentScrollPosition() {
        var top = scrollView.getScrollPosition().top,
          _top = top - fixedHeight;
        if (_top <= 0) {
          return -1;
        }

        var position = Math.min(scope.itemConfig.count - 1,
            Math.floor(_top / itemHeight));

        return position;
      }

      /**
       * 在发生内容区域滑动时的处理器
       */
      scope.$on('linkernav.' + scope.scrollviewName + '.scroll', function() {
        if (state === STATE_LINKER_NAV_SCROLL) {
          return;
        }
        $timeout(function() {
          var linkerNav = getLinkerNavByContentScrollPosition(),
            position = getItemIndexByContentScrollPosition();

          emitItemPositionChangeEvent(position);

          setCurrentLinkerNav(linkerNav);            
        });

      });

      function emitItemPositionChangeEvent(position) {
        if (position !== -1 && position !== currentItemIndex) {
          currentItemIndex = position;
          scope.$emit('linkernav.itemposition.change', position);
          scope.$broadcast('linkernav.itemposition.change', position);
        }
      }

      /**
       * 改变导航项
       * 
       * @param  {String} nav 导航项（id）
       */
      scope.changeLinkerNav = function(nav) {
        if (scope.selectedNav === nav) {
          return;
        }
        
        setCurrentLinkerNav(nav);

        scrollContent(nav);
        scope.$broadcast('linkernav.touch.change', nav);
        scope.$emit('linkernav.touch.change', nav);
      };

      function setCurrentLinkerNav(linkerNav) {
        var position = scope.itemConfig.letterMap[linkerNav];
        if (position >= 0) {
          usefulLinkerNav = linkerNav;
        }
        if(linkerNav === '搜'){
          usefulLinkerNav = linkerNav;
        }
        scope.selectedNav = linkerNav;
        scope.$evalAsync(function() {
          scope.selectedNav = linkerNav;
        });
      }

      /**
       * 滚动内容区域
       * 
       * @param  {String} linkerNav
       */
      function scrollContent(linkerNav) {
        if (linkerNav === '搜') {
          scrollView.scrollTop();
        } else {
          var position = scope.itemConfig.letterMap[linkerNav];
          if (position >= 0) {
            scrollView.scrollTo(0, fixedHeight + position * itemHeight);
            usefulLinkerNav = linkerNav;
          }
        }
      }

      var len = scope.linkerNavs.length,
        navHeight = (height - 21) / len;

      /**
       * 在导航条中滑动
       * 
       * @param  {Event} $event 滑动事件
       */
      scope.onNavMove = function($event) {
        var y = $event.touches[0].clientY - top,
          nav = getLinkerNavByNavPosition(y);

        if (nav) {
          scope.changeLinkerNav(nav);
        }
      };

      /**
       * 通过在导航条上的滑动高度来获取导航项
       * 
       * @param  {Number} y 滑动高度
       * @return {String}   返回导航项id
       */
      function getLinkerNavByNavPosition(y) {
        if (y < 0) {
          return;
        }
        var pos = Math.floor(y / navHeight),
        nav = scope.linkerNavs[pos];
        if(!nav){
          return null;
        }
        nav = nav.id;
        return nav;
      }

      var stopLinkerNavMoveTimer = null;
      /**
       * 触摸开始时处理动作
       * 
       */
      scope.touchstart = function($event) {
        Timer.clear(stopLinkerNavMoveTimer);
        state = STATE_LINKER_NAV_SCROLL;
        scope.start = true;
        scope.onNavMove($event);
      };

      /**
       * 触摸结束后处理动作
       * 
       */
      scope.touchend = function() {
        stopLinkerNavMoveTimer = Timer.delay(function() {
          state = STATE_CONTENT_SCROLL;
        }, 200);
        scope.start = false;

        //滚动到有效的导航条上
        setCurrentLinkerNav(usefulLinkerNav);
      };
    }
  };
});
