package sg.input;

import com.jme.input.ChaseCamera;
import com.jme.input.RelativeMouse;
import com.jme.input.action.InputActionEvent;
import com.jme.input.thirdperson.ThirdPersonMouseLook;
import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.scene.Node;
import com.jme.scene.Spatial;


public class SGThirdPersonHandler extends GlobalInputHandler{
	protected Camera cam;
	protected Node ship;

	public SGThirdPersonHandler(Camera cam, Spatial ship){
		SGChaseCamera ccam = new SGChaseCamera(cam, ship);
		this.addToAttachedHandlers(ccam);
	}

	class SGChaseCamera extends ChaseCamera{
		public SGChaseCamera(Camera arg0, Spatial arg1) {
			super(arg0, arg1);
		}

		protected void setupMouse() {
			RelativeMouse mouse = new RelativeMouse("Mouse Input");
			mouse.registerWithInputHandler(this);

			if (mouseLook != null)
				removeAction(mouseLook);

			mouseLook = new SGThirdPersonMouseLook(mouse, this, target);
			addAction(mouseLook);
		}

		public SGThirdPersonMouseLook getTankMouseLook(){
			return (SGThirdPersonMouseLook) mouseLook;
		}
	}


	class SGThirdPersonMouseLook extends ThirdPersonMouseLook{
		float targetTurnSpeed = 1f;

		public SGThirdPersonMouseLook(RelativeMouse mouse, ChaseCamera camera, Spatial target) {
			super(mouse, camera, target);			
		}

		public void performAction(InputActionEvent event) {
			super.performAction(event);

			//if (mouse.getLocalTranslation().x != 0 || mouse.getLocalTranslation().y != 0) {
			Vector3f camL = camera.getCamera().getLocation();
			//center coordinates to spatial
			float x = target.getLocalTranslation().x - camL.x;
			float z = target.getLocalTranslation().z - camL.z;
			float y = target.getLocalTranslation().y - camL.y;
			float c = FastMath.sqrt(x*x + z*z);

			// Tower rotation
			float angle = FastMath.acos(x/c);
			if(camL.z < 0 && angle > 0) angle = -Math.abs(angle);
			if(camL.z > 0 && angle < 0) angle = Math.abs(angle);
			target.getLocalRotation().fromAngleAxis(angle+FastMath.PI, new Vector3f(0,0,1));

			//gun rotation
			c = FastMath.sqrt(x*x + y*y + z*z);
			angle = FastMath.tan(y/c);
			target.getLocalRotation().fromAngleAxis(angle+FastMath.PI/5, new Vector3f(0,1,0));
			//}
			 
		}
	}
}
