'use strict';

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

angular
  .module('infoDisplay.directives')
  .directive('sinoDrag', sinoDrag);

/** @ngInject */
function sinoDrag($window){
  return {
    restrict: 'AC',
    require: '^sinoModelDrag',
    link: link
  };
  
  function link(scope, element, attrs, ctrl) {
    var startX = 0, startY = 0, x = 0, y = 0,
      floatElement,
      offsetTop,
      offsetLeft,
      startTop,
      startLeft;
      
    element.on('touchstart', function(event) {
      floatElement = element.clone();
      element.after(floatElement);
      
      event.preventDefault();
      
      offsetTop = element[0].offsetTop,
      offsetLeft = element[0].offsetLeft;
      
      startTop = element[0].getBoundingClientRect().top +
        $window.document.documentElement.scrollTop;
      startLeft = element[0].getBoundingClientRect().left;
       
      startX = event.targetTouches[0].pageX;
      startY = event.targetTouches[0].pageY;
      
      floatElement.css({
        zIndex: '10000',
        position: 'absolute',
        top: offsetTop + 'px',
        left: offsetLeft + 'px'
      });
      element.addClass('dragging');
      floatElement.on('touchmove', touchmove);
      floatElement.on('touchend', touchend);
    });
    
    function touchmove(event) {
      x = event.targetTouches[0].pageX - startX;
      y = event.targetTouches[0].pageY - startY;
      floatElement.css({
        transform: 'translate3d(' + x +'px,' + y + 'px, 0)'
      });
      
      ctrl.setItemPosition({
        left: startLeft + x,
        top: startTop + y
      }, scope.$eval(attrs.sinoDrag));
    }
    
    function touchend(event) {
      floatElement.remove();
      element.removeClass('dragging');
      element.unbind('touchmove', touchmove);
      element.unbind('touchend', touchend);
    }
    
  }
}