
var Snap = require('snapsvg');

/* custom plugin */
Snap.plugin(function (Snap, Element, Paper, glob) {
	var elproto = Element.prototype;

	elproto.toBack = function () {
		this.prependTo(this.paper);
	};

	elproto.toFront = function () {
		this.appendTo(this.paper);
	};
});

var paper = null;
var pointData = [];
var config = null;
var readOnly = false;
var startPoint = null;
var drawing_path = null;
var canDraw = false;
var rectZone = null;
var PATH_COLOR = "#ff00ff";
var READ_ONLY_STOKE = "";
var READ_ONLY_FILL = "";

var SELECTED_COLOR = "#ffff00";
var FIRST_NODE_COLOR = "#FF0000";
var HANDLE_SIZE = 6;
var isDragged = false;
var enablePoint = true;
var pathIsClosed = false;
var ENABLE_NEW_NODE = true;
var RECT_MODE ='RECT';
var drawingMode = RECT_MODE; //free
var FREE_MODE = 'FREE';
var availableModes = [RECT_MODE, FREE_MODE];

var getId = (function () {
		var cpt = 0;
		var defautPrefix = "item_"; 
		return function (prefix) {
			prefix = (typeof prefix === 'string') ? prefix : defautPrefix;
			cpt = cpt + 1;
			return prefix + cpt; 
		}
	}());



var pathToPoint = function (path) {

};

var handleRectPath = function (path) {
	if (readOnly) {
		paper.path(path).attr({ stroke:'red', opacity: 0.6});
		return;
	}

	var pathInfos = Snap.parsePathString(path);
	drawing_path = paper.path(path);
	drawing_path.attr({stroke:'white', opacity: 0.4});
	handlePathClosed();
};

var handlePathClosed = function () {
	if (drawing_path) {
		drawing_path.drag();
	}
}

var handleFreePath = function (path) {

	if (readOnly) {
		
		paper.path(path).attr({
			stoke: 'orange',
			fill: 'orange',
			opacity: 0.5,
		});

		return; 
	}

	var pathInfos = Snap.parsePathString(path);
	pathInfos.map(function (pathData) {
		if(pathData[0] !== 'Z') {
			createPoint(paper, pathData[1], pathData[2], pointData);
		} else {
			pathIsClosed = true;
			updatePath(paper, onClosePath);
		}
	});

	/* replay the path here */

}; 
//transform point to path
var updatePath = function (paper, updateCallback) {
	var path = "M";

	if (pointData.length <= 1) {
		return;
	}

	path += pointData[0].x + ',' + pointData[0].y;

	for (var i=0; i < pointData.length; i++) {
		if (i == 0) continue;

		var pointInfos = pointData[i];
		lPath = "L" + pointInfos.x + "," + pointInfos.y;
		path += " " + lPath;
	}
	
	path += (pathIsClosed) ? " Z": "";
	
	console.log("stra", updateCallback);

	if (typeof updateCallback === 'function' && pathIsClosed) {
		updateCallback();
	}
		
	/* remove prev path */
	if (drawing_path) {
		drawing_path.remove();
	}	

	drawing_path = paper.path(path);

	drawing_path.attr({
		stroke: "red",
		opacity: 0.6
	});
	
	/* bring all handler to front */
	pointData.map(function (point) {
		if (point.handler) {
			point.handler.toFront();
		}
	});

	console.log("radical...", path);
	console.log({isDragged: isDragged, enablePoint: enablePoint, pathIsClosed: pathIsClosed});
};

var onClosePath = function () {
	ENABLE_NEW_NODE = false;
	/* Group path an handler - add remove_btn */
	jQuery("#action-wrapper").show();
};


var onClickOnHandler = function (point, p, e) {
	//close path
	console.log("new click handler ...");
	if (point.isFirst && pointData.length > 2) {
		pathIsClosed = true;
	}
};

var updatePointPosition = function (newPoint, x, y) {
	var index = pointData.indexOf(newPoint);
	if (index !== -1) {
		pointData[index].x = x;
		pointData[index].y = y; 
		return true;
	} else {
		return false;
	}
};

var clearPreviousPath = function () {
	drawing_path.remove();
};

var onMoveHandler = function (dx, dy, posX, posY, e) {
	console.log("in onMoveHandler...");
	isDragged = true;
	/* update point then update the view */
	var transformValue = this.data('origTransform') + (this.data('origTransform') ? "T" : "t") + [dx, dy];
	this.attr({ transform: transformValue});
	var boxSize = this.getBBox();

	var wasUpdated = updatePointPosition(this.data('point'), boxSize.x + (HANDLE_SIZE / 2) , boxSize.y + (HANDLE_SIZE / 2));
	
	if (wasUpdated) {
		updatePath(this.paper);
	}
}

var bindHandlerEvent = function (point, p) {
	point.handler.click(onClickOnHandler.bind(this, point, p));
	/* -- handler -- */
	point.handler.hover(function () {
		point.handler.attr({fill: 'yellow'});
	}, function () {
		var fillColor = point.isFirst ? FIRST_NODE_COLOR : "";
		point.handler.attr({fill: fillColor});
	});
	
	point.handler.drag(onMoveHandler, function () {
        this.data('origTransform', this.transform().local );
	}, function () {
		if (!isDragged) { return true; }
		isDragged = false;
		enablePoint = false;
	});
}

var createPointHandler = function (p, point) {

	var handleX = point.x - HANDLE_SIZE/2;
	var handleY = point.y - HANDLE_SIZE/2;

	handler = p.rect(handleX, handleY, HANDLE_SIZE, HANDLE_SIZE);

	point.handler = handler;
	point.handler.data('point', point);
	if (pointData.length === 0) {
		point.isFirst = true;
	}
	
	bindHandlerEvent(point, p);
	point.handler.attr({
		fill: (pointData.length === 0) ? FIRST_NODE_COLOR : "",
		opacity: 0.9,
		stroke: PATH_COLOR
	});

	return point;
}

//create paper
var createPoint = function (paper, x, y, pointData) {

	var point = {x:x, y:y, id: getId()};
	
	/**/
	if (pathIsClosed) {
		updatePath(paper, onClosePath);
		return;
	}

	if (!enablePoint) {
		enablePoint = true;
		return false;
	}

	point = createPointHandler(paper, point);
	pointData.push(point);
	updatePath(paper);
};


var attachRectEvents = function (paper) {
	if (readOnly) { return false; }

	var startPosition = {};
	var currentPosition = {};
	/* add resizer */

	paper.mousedown(function (e) {
		if (drawingMode === FREE_MODE || pathIsClosed) { return; }
		startPosition.x = e.offsetX;
		startPosition.y = e.offsetY;
		canDraw = true;
	});

	paper.mousemove(function (e) {
		if (drawingMode === FREE_MODE) { return; }
		if (!canDraw) { return; }
		var x, y;
		currentPosition.x = e.offsetX;
		currentPosition.y = e.offsetY;
		
		if (rectZone) {
			rectZone.remove();
		}

		/* bas -> droite */
		var width = Math.abs(currentPosition.x - startPosition.x);
		var height = Math.abs(startPosition.y - currentPosition.y);

		if (currentPosition.y > startPosition.y && currentPosition.x > startPosition.x) {
			x = startPosition.x;
			y = startPosition.y;	
		}
		
		/* haut -> droite */
		if (currentPosition.y < startPosition.y && currentPosition.x > startPosition.x) {
			x = currentPosition.x - width;
			y = currentPosition.y; 
		}
		
		/* haut -> gauche */
		if (currentPosition.y < startPosition.y && currentPosition.x < startPosition.x) {
			x = currentPosition.x;
			y = currentPosition.y;
		}

		/* bas -> gauche */
		if (currentPosition.y > startPosition.y && currentPosition.x < startPosition.x) {
			x = currentPosition.x
			y = currentPosition.y - height;
		}
		if(!x || !y) { return; }		
		rectZone = paper.rect(x, y, width, height);
		rectZone.attr({opacity: 0.4});
	});


	paper.mouseup(function () {
		if ((drawingMode === FREE_MODE) || pathIsClosed || !rectZone) { return false; }
		rectZone.drag();
		drawing_path = rectZone;
		canDraw = false;
		pathIsClosed = true;
	});
};

var attachPointEvents = function (paper) {
	if (readOnly) { return; }
	paper.click( function(e) {
		if (drawingMode === RECT_MODE) {
			return true;
		}

		if (!ENABLE_NEW_NODE) { return true; }
		createPoint(paper, e.offsetX, e.offsetY, pointData);
	});
};

var API = {
	
	setPath: function (pathString) {
		/* redraw the path */
		var pathInfos = pathString.split(';');
		if( availableModes.indexOf(pathInfos[1]) === -1) {
			new Error("drawing mode: [" + pathInfos[1] + "] is not available");
		}

		this.setDrawingMode(pathInfos[1]);
		if (pathInfos.length === 1) {
			new Error("A drawing mode must be provided");
		}

		if (pathInfos.length >= 2) {
			var path = pathInfos[0];
			if (pathInfos[1] === RECT_MODE) {
				handleRectPath(path);
			}
			
			if (pathInfos[1] === FREE_MODE) {
				handleFreePath(path);
			}
		}
	},

	setDrawingMode: function (mode) {
		if (availableModes.indexOf(mode) !== -1) {
			drawingMode = mode;
		}
		this.clear();
	},
	
	clear: function () {
		/* clear previous path, point, handler */
		pointData.map(function (point) {
			if (point.handler) {
				point.handler.remove();
			}
		});

		/*clear path is exists*/
		 if (drawing_path) {

		 	console.log(drawingMode);
		 	alert("rads");
		 	if (drawingMode === RECT_MODE) {
		 		alert("radical ... ");
		 		console.log("radical ... ");
		 		console.log(drawing_path.getBBox().path.toString());
		 	}
		 	//drawing_path.getBBox().path.toString()
		 	drawing_path.remove();
		 }		
		 


		pointData = [];
		startPoint = null;
		drawing_path = null;
		isDragged = false;
		enablePoint = true;
		pathIsClosed = false;
		ENABLE_NEW_NODE = true;
	},

	getPath: function () {
		/* retourne le chemin */
		/* send path and BBox | implement edit and load path */
		var path = "";
		if (drawing_path) {
			if (drawingMode === RECT_MODE) {
				path = Snap.path.toAbsolute(drawing_path.getBBox().path).toString();
			}
			else {
				path = drawing_path.attr('d');
			}
		}
		/* save path should be normalized */
		//taille/10
		var xRatio = 1/7;
		var yRatio = 1/4.3;
		var transformMatrix = Snap.matrix(xRatio.toFixed(2), 0, 0, yRatio.toFixed(2), 0, 0);
		console.log(transformMatrix);
		console.log(path);
		newPath = Snap.path.map(path,transformMatrix).toString();
		console.log(newPath);
		test = paper.path(newPath);
		console.log(test);
		//should be normalize

		//[sx 0 0 sy 0 0]. One unit in the X and Y directions in the new coordinate system equals sx and sy units in the previous coordinate system, respectively.

		return path;
	}
};

module.exports = {

	init: function(config) {
		/* strange ... */
		var mainImage = jQuery(config.wrapperId).find('img').eq(0);
		var cutCanvas = jQuery(config.wrapperId).find('.cut-canvas').eq(0);
		var path = jQuery(config.wrapperId).find('.image-path').eq(0);
		
		if (path.length) {
			jQuery(cutCanvas).append(path);
		}
		
		if (!cutCanvas.length) {
			var cutCanvas = jQuery('<svg version="1.1"></svg>').addClass('cut-canvas');
			cutCanvas.css({border: "1px solid red"});
			jQuery(config.wrapperId).append(cutCanvas);
		}

		if (!mainImage) {
			new Error(config.wrapperId + "Can't be found ...");
		}

		cutCanvas.css({
			position: 'absolute', 
			top: '0px', 
			left: '15px', //margin from bootstrap
			marginLeft: 'auto',
			marginRight: 'auto',
			width: mainImage.width(),
			height: mainImage.height(),
			viewBox: '0 0 100 100'
		});

		if (typeof config.readOnly === 'boolean' && config.readOnly === true) {
			readOnly = true;
		}

		paper = new Snap(cutCanvas.get(0));

		/* handle drawin here */
		attachPointEvents(paper);
		attachRectEvents(paper);

		return API;
	},
};