var angular = require('angular');
require('../modules');

angular
  .module('commons.directives')
  .directive('sinoListScrollDelegate', sinoListScrollDelegate);

/** @ngInject */
function sinoListScrollDelegate($ionicScrollDelegate, $window, $timeout, $ionicGesture) {

  return {
    restrict: 'A',
    require: '^?sinoListTabs',
    compile: compile
  };

  function compile(element, attrs) {
    var time = new Date().getTime();
    var delegateName = 'delegate-' + time;
    attrs.$set('delegateHandle', delegateName);

    return link;
  }

  function link(scope, element, attrs, ctrl) {
    var dragleftGesture,
      dragrightGesture,
      dragendGesture,
      dragUpGesture,
      dragDownGesture,
      dragStartGesture;

    $timeout(function() {
      ctrl.setScrollDelegate(attrs.sinoListScrollDelegate,
        $ionicScrollDelegate.$getByHandle(attrs.delegateHandle));
    });

    var startScroll = false;

    var $ionView = element;
    dragStartGesture = $ionicGesture.on('touch', onTouch, $ionView);
    dragleftGesture = $ionicGesture.on('dragleft', onDragVertical, $ionView);
    dragrightGesture = $ionicGesture.on('dragright', onDragVertical, $ionView);
    dragUpGesture = $ionicGesture.on('dragup', onDragY, $ionView);
    dragDownGesture = $ionicGesture.on('dragdown', onDragY, $ionView);
    dragendGesture = $ionicGesture.on('release', onRelease, $ionView);

    function onTouch() {
      ctrl.getSwipe().freezeScroll(true);
    }

    function onDragVertical() {
      if (!startScroll) {
        startScroll = true;
        ctrl.getSwipe().freezeScroll(false);
        $ionicScrollDelegate.$getByHandle(attrs.delegateHandle).freezeScroll(true);
      }
    }

    function onDragY() {
       if (!startScroll) {
        startScroll = true;
        ctrl.getSwipe().freezeScroll(true);
      }
    }

    function onRelease() {
      startScroll = false;
      $ionicScrollDelegate.$getByHandle(attrs.delegateHandle).freezeScroll(false);
      ctrl.getSwipe().freezeScroll();
    }


    scope.$on('$destroy', function() {
      $ionicGesture.off(dragStartGesture, 'touch', onTouch);
      $ionicGesture.off(dragleftGesture, 'dragleft', onDragVertical);
      $ionicGesture.off(dragrightGesture, 'dragright', onDragVertical);
      $ionicGesture.off(dragUpGesture, 'dragup', onDragY);
      $ionicGesture.off(dragDownGesture, 'dragdown', onDragY);
      $ionicGesture.off(dragendGesture, 'release', onRelease);
    });
  }
}
