import com.sun.jna.Memory;

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;


public class TakeDown extends ScriptEngine {
	private int index = 0;
	@Override
	public int loop() throws Exception {
		for (int index = 0; index < 2048; index++) {
			if(getType(index) == 12 || getType(index) == 13) {
				this.index = index;
				//aimAt();
			}
		}
		return 200;
	}

	public int getType(int index) {
		return MemoryHack.readMemory(Constants.OFF_ENTITY + index
				* Constants.OFF_ENTITY_SIZE + 0x00D4 , 4).getInt(0);
	}
	
	public float[] getRawLocation(int index) {
		Memory test = MemoryHack.readMemory(Constants.OFF_ENTITY + index
				* Constants.OFF_ENTITY_SIZE + 0x0014, 14);
		return new float[] { test.getFloat(0), test.getFloat(4),
				test.getFloat(8) };
	}
	
	public float[] getAnglesTo() {
		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(getRawLocation(this.index),
				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 local = getLocalPlayer();
		if (local == null)
			return false;

		Memory angleBuffer = MemoryHack
				.readMemory(Constants.VIEWANGLEBUFFER, 8);

		float[] angles = getAnglesTo();

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

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

}
