"use strict";
/* nullifies target's controls, optionally for a set number of inputs */

var GO_Holdshield = function(target, durability){
	this.sprite = new Sprite(GO_Holdshield.spriteSheet,"Holdshield");
	this.sprite.collision_flags = 
		DEFINE_SPRITE_COLLISION_FLAGS.SPRITES_PASSIVE;
	this.sprite.setBoundingBox(
		0,
		0,
		15,
		15);
	//sprite.constraints=constraints;
	this.sprite.max_step = 0;
	this.sprite.game_object = this; // no longer a generic GO

	this.target = target;
	this.durability = durability ? durability : -1;

	this.last_controls = {};
};
GO_Holdshield.spriteImg = SDS_Load_Image("art/sheets/sprite/holdshield.png");
GO_Holdshield.spriteSheet = new TileSheet(4, 4, 1, 0, GO_Holdshield.spriteImg);

GO_Holdshield.prototype = new GameObject(
	new Sprite(
		GO_Holdshield.spriteSheet,
		"Holdshield"
	),
	"Holdshield"
	);

	GO_Holdshield.prototype.interactions = 0;

	GO_Holdshield.prototype.Update = function(){
		if (this.target){
			//this.sprite.x = this.target.sprite.center.x - 8;
			//this.sprite.y = this.target.sprite.center.y - 8;
			this.sprite.move(
				(this.target.sprite.x+this.target.sprite.center.x - this.sprite.x-this.sprite.center.x)>>2,
				(this.target.sprite.y+this.target.sprite.center.y - this.sprite.y-this.sprite.center.y)>>2,
			);
			if (Math.abs(this.target.sprite.x+this.target.sprite.center.x - this.sprite.x-this.sprite.center.x)<4){
				this.sprite.x = this.target.sprite.x+this.target.sprite.center.x-this.sprite.center.x;
			}
			if (Math.abs(this.target.sprite.y+this.target.sprite.center.y - this.sprite.y-this.sprite.center.y)<4){
				this.sprite.y = this.target.sprite.y+this.target.sprite.center.y-this.sprite.center.y;
			}
			if ((this.target.interactions & DEFINE_GAMEOBJECT_INTERACTIONS.CONTROL) && this.sprite.isTouchingSprite(this.target.sprite)){
				for (this._heap.c in DEFINE_CONTROLS_KEYCODES){
					// wanted to specifically react to .pressed[], but Controls.Update
					// is called by GameObjectManager right after the object's Update
					// and Controls.Update clears the frame's .pressed/.released
					// so the shield would only see them if it ran before the target
					// which will never happen if the shield is added to the room
					// after the target.
					if (this.durability>0 && this.target.controls.held[this._heap.c] && !this.last_controls[this._heap.c]){
						--this.durability;
					}
					// instead, do our own hold filtering
					this.last_controls[this._heap.c] = this.target.controls.held[this._heap.c];
					
					//this.target.controls.unpress(this.target.controls,this._heap.c);
				}
				// unpress in separate loop so last-pressed buttons can persist
				if (this.durability>0){
					for (this._heap.c in DEFINE_CONTROLS_KEYCODES){
						this.target.controls.unpress(this.target.controls,this._heap.c);
					}
				}
			}
		}
		if (this.durability==0){
			this.sprite.map_room.removeSprite(this.sprite);
			this.manager.remove(this);
		}


		this.sprite.frame = this.sprite.frame ^ 1;
	};

