"use strict";

var GO_Button = function(targetObj){
	this.sprite = new Sprite(GO_Button.spriteSheet,"Button");
	this.sprite.collision_flags = 
		DEFINE_SPRITE_COLLISION_FLAGS.SPRITES_PASSIVE;
	this.sprite.setBoundingBox(0,2,15,7);
	this.sprite.game_object = this; // no longer a generic GO

	this.target_obj_name = targetObj ? targetObj : null; // name of GameObject with interaction SIGNALABLE
	this.target_obj = null;
	this.sticky = false; // will stay pressed once triggered
	this.pressed = false;
	this.pressed_pending = false;
	// if pressed by trigger (i.e. Meli touch), disable DAMAGE interaction
	// so kickwaves and thrown projectiles don't bounce
	this.pressed_by_trigger = false; 
};
GO_Button.spriteImg = SDS_Load_Image("art/sheets/sprite/button.png");
GO_Button.spriteSheet = new TileSheet(4, 3, 1, 0, GO_Button.spriteImg);

GO_Button.prototype = new GameObject(
	new Sprite(
		GO_Button.spriteSheet,
		"Button"
	),
	"Button"
	);

	GO_Button.prototype.interactions = 
		DEFINE_GAMEOBJECT_INTERACTIONS.TRIGGER | 
		DEFINE_GAMEOBJECT_INTERACTIONS.DAMAGE;

	GO_Button.prototype.triggerEvent = function(sourceGO){
		this.pressed_pending=true;
		this.pressed_by_trigger=true;
		return null;
	};
	GO_Button.prototype.damage = function(sourceGO){
		this.pressed_pending=true;
		return true; // always "die" for purposes of not destroying blocks
	};

	GO_Button.prototype.Update = function(){
		this._heap.wasPressed = false;
		this._heap.wasReleased = false;
		
		this._heap.newpressed = (this.pressed && this.sticky) || this.pressed_pending;
		this._heap.wasPressed = this._heap.newpressed && !this.pressed;
		this._heap.wasReleased = this.pressed && !this._heap.newpressed;
		this.pressed = this._heap.newpressed;
		this.pressed_pending=false;

		if (this.pressed_by_trigger){
			this.interactions &= ~DEFINE_GAMEOBJECT_INTERACTIONS.DAMAGE;
		}
		else{
			this.interactions |= DEFINE_GAMEOBJECT_INTERACTIONS.DAMAGE;
		}
		this.pressed_by_trigger=false;

		if ((this._heap.wasPressed || this._heap.wasReleased) && !this.target_obj){
			this.target_obj = this.manager.getNamedObject(this.target_obj_name);
		}
		if ((this._heap.wasPressed || this._heap.wasReleased) && this.target_obj){
			if (this._heap.wasPressed) this.target_obj.signal(this,1);
			if (this._heap.wasReleased) this.target_obj.signal(this,-1);
		}

		if (this._heap.wasPressed){
			this.sfx = new Chiptune("FX_switchon",SDS.sfxchip);
			this.sfx.play(false);
		}
		if (this._heap.wasReleased){
			this.sfx = new Chiptune("FX_switchoff",SDS.sfxchip);
			this.sfx.play(false);
		}

		this.sprite.frame = this.pressed ? 1 : 0;
	};
