'use strict';

const debounce = require("debounce");
const defaultValue = require("default-value");

const selectable = require("./selectable");

module.exports = function($) {
	selectable($);

	$.fn.draggable = function(options = {}) {
		let debounceInterval = defaultValue(options.debounce, 10);

		this.on("mousedown", (event) => {
			let startX = event.pageX;
			let startY = event.pageY;

			let moveHandler = debounce((event) => {
				this.trigger("draggable:move", [{
					offsetX: event.pageX - startX,
					offsetY: event.pageY - startY
				}]);
			}, debounceInterval);

			$(document).on("mousemove", moveHandler);

			$(document).one("mouseup", (event) => {
				$(document).off("mousemove", moveHandler);
				$(document).enableSelection();

				this.trigger("draggable:end");
			});

			$(document).disableSelection();

			this.trigger("draggable:start");
		});
	}
}