import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import com.sun.jna.Memory;

import net.mw3.etewt3.handlers.GameInput;
import net.mw3.etewt3.handlers.MWPlayer;
import net.mw3.etewt3.handlers.MemoryHack;
import net.mw3.etewt3.script.ScriptEngine;
import net.mw3.etewt3.utils.Constants;
import net.mw3.etewt3.utils.Vector;


/**
 * @author Mark Gore
 * 
 */
public class AutoKnife extends ScriptEngine {

	@Override
	public int loop() throws Exception {
		MWPlayer player = getNearest();
		if(player != null) {
			int aim = 15;
			double dist = 3;
			if(player.isProne()) {
				aim = 65;
				dist = 1.3;
			}
			if(player.getDistance() <= dist) {
				if(aimAt(player, aim)) {
					if(dist > 1.3)
						dist = 2.5;
					if(player.getDistance() <= dist) {
						Robot robot = new Robot();
						robot.keyPress(KeyEvent.VK_E);
						robot.keyRelease(KeyEvent.VK_E);
						sleep(1500);
					} 
				}
				return 10;
			}
		}
		return 100;
	}

	@Override
	public boolean onStart() {
		// TODO Auto-generated method stub
		return true;
	}
	
	public float[] getAnglesTo(MWPlayer target) {
		Memory viewAxisBuffer = MemoryHack.readMemory(Constants.REFDEF + 0x24, 36);
		float[][] viewAxis = new float[3][3];
		int index = 0;
		for (int i = 0; i < 3; i++) {
			viewAxis[i][0] = viewAxisBuffer.getFloat(index++ * 4);
			viewAxis[i][1] = viewAxisBuffer.getFloat(index++ * 4);
			viewAxis[i][2] = viewAxisBuffer.getFloat(index++ * 4);
		}

		float[] vector = Vector.vectorSubtract(
				target.getRawLocation(),
				getLocalPlayer().getRawLocation());

		vector = Vector.normalize(vector);

		return new float[]{
				(float) Vector.toDegree((float) Math.asin(Vector.dotProduct(viewAxis[1], vector))),
				(float) Vector.toDegree((float) -Math.asin(Vector.dotProduct(viewAxis[2],vector)))
		};
	}

	public boolean aimAt(MWPlayer target, double verticalOffset) {
		MWPlayer local = getLocalPlayer();
		if(target == null || local == null)
			return false;

		Memory angleBuffer = MemoryHack.readMemory(Constants.VIEWANGLEBUFFER, 8);
		
		float[] angles = getAnglesTo(target);

		angles[0] += angleBuffer.getFloat(4);
		angles[1] += angleBuffer.getFloat(0) + verticalOffset;

		MemoryHack.writeMemory(Constants.VIEWANGLEBUFFER, new float[] {angles[1], angles[0]}, 8);
		return true;
	}

}