'use strict';

function TouchBehavior(dom, options) {
  var startDistance;
  var ignoreTouch;
  init(dom);
  function init(element) {
    if (typeof $.fn.kendoTouch === "function") {
      try {
        $(element).on("mousedown", () => {
          ignoreTouch = true;
        }).on("mouseup", () => {
          ignoreTouch = false;
        }).kendoTouch({
          multiTouch: true,
          enableSwipe: true,
          swipe: (e) => {
            if (!ignoreTouch) {
              onSwipe(e);
            }
          },
          gesturestart: (e) => {
            if (!ignoreTouch) {
              onGestureStart(e);
            }
          },
          gestureend: (e) => {
            if (!ignoreTouch) {
              onGestureEnd(e);
            }
          },
          gesturechange: (e) => {
            if (!ignoreTouch) {
              onGestureChange(e);
            }
          },
          doubletap: (e) => {
            if (!ignoreTouch) {
              onDoubleTap(e);
            }
          },
          touchstart: (e) => {
            if (!ignoreTouch) {
              fire("touchstart");
            }
          }
        });
      } catch (e) {
        console.error("Instantiation of Kendo Touch threw an exception", e);
        throw e;
      }
    }
  }
  function onDoubleTap(e) {
    fire("doubletap", e);
  }
  function onGestureStart(e) {
    startDistance = kendo.touchDelta(e.touches[0], e.touches[1]).distance;
  }
  function onGestureEnd(e) {
  }
  function onGestureChange(e) {
    var current = kendo.touchDelta(e.touches[0], e.touches[1]).distance;
    onPinch({
      distance: current,
      lastDistance: startDistance
    });
    startDistance = current;
  }
  function onSwipe(e) {
    fire("swipe", e);
  }
  function onPinch(e) {
    fire("pinch", e);
  }
  function fire(func, args) {
    var handler = options[func];
    if (typeof handler === "function") {
      handler(args);
    }
  }
}

exports.TouchBehavior = TouchBehavior;
