import node;

//constants
var SPEED: int const = 5;

//variables
var parent: opaque = null; //cache the parent for quick access
var posX: int = 50;
var posY: int = 50;
var WIDTH: int const = 143;
var HEIGHT: int const = 75;

var xspeed: int = 0;
var yspeed: int = 0;

//accessors - variables are private, functions are public
fn getX(node: opaque) {
	return posX;
}

fn getY(node: opaque) {
	return posY;
}

//lifecycle functions
fn onLoad(node: opaque) {
	print "onLoad() called";
}

fn onInit(node: opaque) {
	print "onInit() called";

	parent = node.getParentNode();
	node.loadTexture("sprites:/little_plane.png");
}

fn onStep(node: opaque) {
//	print "onStep() called";

	posX += xspeed;
	posY += yspeed;
}

fn onFree(node: opaque) {
	print "onFree() called";

	node.freeTexture();
}

fn onDraw(node: opaque) {
//	print "onDraw() called";

	var px = 0;
	var py = 0;

	if (parent != null) {
		px = parent.callNodeFn("getX");
		py = parent.callNodeFn("getY");
	}

	node.drawNode(posX + px, posY + py, WIDTH, HEIGHT);
}

//event functions
fn onKeyDown(node: opaque, event: string) {
	if (event == "character_up") {
		yspeed -= SPEED;
		return;
	}

	if (event == "character_down") {
		yspeed += SPEED;
		return;
	}

	if (event == "character_left") {
		xspeed -= SPEED;
		return;
	}

	if (event == "character_right") {
		xspeed += SPEED;
		return;
	}
}

fn onKeyUp(node: opaque, event: string) {
	if (event == "character_up" && yspeed < 0) {
		yspeed = 0;
		return;
	}

	if (event == "character_down" && yspeed > 0) {
		yspeed = 0;
		return;
	}

	if (event == "character_left" && xspeed < 0) {
		xspeed = 0;
		return;
	}

	if (event == "character_right" && xspeed > 0) {
		xspeed = 0;
		return;
	}
}

fn onMouseMotion(node: opaque, x: int, y: int, xrel: int, yrel: int) {
	// print "entity.toy:onMouseMotion(" + string x + ", " + string y + ", " + string xrel + ", " + string yrel + ")";
}

fn onMouseButtonDown(node: opaque, x: int, y: int, button: string) {
	// print "entity.toy:onMouseButtonDown(" + string x + ", " + string y + ", " + button + ")";

	//jump to pos
	posX = x - WIDTH / 2;
	posY = y - HEIGHT / 2;
}

fn onMouseButtonUp(node: opaque, x: int, y: int, button: string) {
	// print "entity.toy:onMouseButtonUp(" + string x + ", " + string y + ", " + button + ")";
}

fn onMouseWheel(node: opaque, xrel: int, yrel: int) {
	// print "entity.toy:onMouseWheel(" + string xrel + ", " + string yrel + ")";
}

