/**
 *
 * @project        Motion Detection in JS
 * @file           ImageCompare.js
 * @description    Core functionality.
 * @author         Benjamin Horn
 * @package        MotionDetector
 * @version        -
 *
 */

;(function(App) {

	"use strict";

	/*
	 * The core motion detector. Does all the work.
	 *
	 * @return <Object> The initalized object.
	 *
	 */
	App.Core = function() {

		var rendering = false;

		var width = 64;
		var height = 48;

		var webCam = null;
		var imageCompare = null;

		var currentImage = null;
		var oldImage = null;

		var topLeft = [Infinity,Infinity];
		var bottomRight = [0,0];



		/*
		 * Initializes the object.
		 *
		 * @return void.
		 *
		 */
		function initialize() {
			imageCompare = new App.ImageCompare();
			webCam = new App.WebCamCapture(document.getElementById('webCamWindow'));

			rendering = true;

			if(rendering == true) {
				setInterval(function(){main()}, 100)
			}
		}

		/*
		 * Compares to images and updates the position
		 * of the motion div.
		 *
		 * @return void.
		 *
		 */
		function render() {
			oldImage = currentImage;
			currentImage = webCam.captureImage(false);

			if(!oldImage || !currentImage) {
				return;
			}

			var vals = imageCompare.compare(currentImage, oldImage, width, height);

			topLeft[0] = vals.topLeft[0] * 10;
			topLeft[1] = vals.topLeft[1] * 10;

			bottomRight[0] = vals.bottomRight[0] * 10;
			bottomRight[1] = vals.bottomRight[1] * 10;



			/*
			document.getElementById('movement').style.top = topLeft[1] + 'px';
			document.getElementById('movement').style.left = topLeft[0] + 'px';

			document.getElementById('movement').style.width = (bottomRight[0] - topLeft[0]) + 'px';
			document.getElementById('movement').style.height = (bottomRight[1] - topLeft[1]) + 'px';
			*/
			if (topLeft[0]!=Infinity && topLeft[1]!=Infinity) {

				var avX = (topLeft[0]+bottomRight[0])/2;
				var avY = (topLeft[1]+bottomRight[1])/2;

				if (avX < (width*10)/3) console.log("RIGHT")
				if (avX > (width*10)/3 && avX < 2*(width*10)/3) console.log("MIDDLE")
				if (avX > 2*(width*10)/3) console.log("LEFT")
				//console.log((topLeft[0]+bottomRight[0])/2+" "+(topLeft[1]+bottomRight[1])/2)

				//console.log(topLeft[0]+(bottomRight[0]-topLeft[0])/2 + " " + topLeft[1]+(bottomRight[1]-topLeft[1])/2)
				//console.log(topLeft[0] + " "+topLeft[1]+" "+bottomRight[0]+" "+bottomRight[1])
			}


			topLeft = [Infinity,Infinity];
			bottomRight = [0,0]
			return;
		}

		/*
		 * The main rendering loop.
		 *
		 * @return void.
		 *
		 */
		function main() {
			try{
				render();
			} catch(e) {
				console.log(e);
				return;
			}

			return;
		}

		initialize();
	};
})(MotionDetector);
