"use strict";
/* A lesser spirit of plants.  Knows how to raise a Sky Tree. */
var GO_Lief = function(){
	this.sprite = new Sprite(GO_Lief.spriteSheet,"Lief");
	this.sprite.collision_flags = 
		DEFINE_SPRITE_COLLISION_FLAGS.GROUND | 
		DEFINE_SPRITE_COLLISION_FLAGS.SPRITES_ACTIVE |
		DEFINE_SPRITE_COLLISION_FLAGS.SPRITES_PASSIVE;
	this.sprite.setBoundingBox(2,0,13,15);
	this.sprite.game_object = this; // no longer a generic GO

	this.controls = new Controls(); // just to init

	this.horizontal_move_index=0;
	this.vertical_move_index = 0;
	this.anim_state = this.ANIM_STATES.idle;
	this.frame_timer=0;

	this.direction = 1; // +/-1 for facing

	this.idle_timer = 0;

	this.sleeping = false;
};
GO_Lief.spriteImg = SDS_Load_Image("art/sheets/sprite/treespirit.png");
GO_Lief.spriteSheet = new TileSheet(4, 4, 2, 2, GO_Lief.spriteImg);

GO_Lief.prototype = new GameObject(
	new Sprite(
		GO_Lief.spriteSheet,
		"Lief"
	),
	"Lief"
	);

	GO_Lief.prototype.interactions = 
		DEFINE_GAMEOBJECT_INTERACTIONS.CONTROL |
		DEFINE_GAMEOBJECT_INTERACTIONS.CHECK;


	GO_Lief.prototype.ANIM_STATES = {
		"idle" : 0,
		"bloom" : 1
	};
	GO_Lief.prototype.anim_frames = [
		[0,1,2], //"idle" : 
		[4,5,6,7], //"bloom" :
	];

	GO_Lief.prototype.checkEvent = function(sourceGO){
		if (this.sleeping) return "GD_Lief_sleeps";

		if (sourceGO && sourceGO.sprite) this.direction = (sourceGO.sprite.x<this.sprite.x) ? -1 : 1;
		
		this.idle_timer = 0;
		this.anim_state = this.ANIM_STATES.bob;
		this.frame_timer=0;
		
		return Dialogue_getCurrentEvent["Lief"]();
	};

	GO_Lief.prototype.Update = function(){

		this._heap.oldAnimState = this.anim_state;

		this.idle_timer++;

		
		this.anim_state = this.controls.held.A ? this.ANIM_STATES.bloom : this.ANIM_STATES.idle;

		if (this.controls.pressed.left) this.direction = -1;
		if (this.controls.pressed.right) this.direction = 1;

		if (this._heap.oldAnimState != this.anim_state){
			this.frame_timer=0;
		}
		
		// special case for idle
		if (this.anim_state==this.ANIM_STATES.idle){
			this._heap.aniFrame = 
				((this.frame_timer>>3)&7) ^
				((this.frame_timer>>5)&7) ^
				((this.frame_timer>>6)&7) ^
				((this.frame_timer>>8)&7) ^
				((this.frame_timer>>9)&7);
			// empirically, I want to cut ~half the current blinks and turnt hem into leaf twitches.
			// so.  up from &3 to &7 and specially handle the 4+ case
			if (this._heap.aniFrame & 4){
				if (this._heap.aniFrame & 1) this._heap.aniFrame = 2;
				else this._heap.aniFrame &= 3;
			}
			if (this._heap.aniFrame === 3) this._heap.aniFrame = 0;

			++this.frame_timer;
			this.frame_timer &= 1023;
		}
		else{
			this._heap.aniFrame = (this.frame_timer>>2);
			if (this.frame_timer<15) ++this.frame_timer;
		}

		if (this.sleeping) this.sprite.frame = 1;
		else this.sprite.frame = this.anim_frames[this.anim_state][this._heap.aniFrame];

		this.sprite.frame = this.sprite.frame & 7;
		if (this.direction<0) this.sprite.frame+=8;
	};

