/*
* A switchable gate which moves its height vertically
*/
"use strict";

var GO_SwitchGate = function(opensDown,switchCount){
	this.sprite = new Sprite(GO_SwitchGate.spriteSheet,"Gate");
	this.sprite.collision_flags = 
		DEFINE_SPRITE_COLLISION_FLAGS.GROUND | 
		DEFINE_SPRITE_COLLISION_FLAGS.SPRITES_ACTIVE |
		DEFINE_SPRITE_COLLISION_FLAGS.SPRITES_PASSIVE |
		DEFINE_SPRITE_COLLISION_FLAGS.SOLID;
	this.sprite.setBoundingBox(0,0,15,31);
	//this.sprite.constraints=constraints;
	this.sprite.max_step = 0;
	this.sprite.game_object = this; // no longer a generic GO

	this.switch_total = switchCount ? switchCount : 1; // how many switches are needed to open the gate
	this.switch_current = 0; // how many switches are currently contributing
	this.opened = false;
	this.sticky=false; // stay in activated position once attained
	this.jiggle=0; // countdown to be temporarily open
	this.dejiggle = 0; // countdown to be sure we're closed so gates can't be jiggled all the way open

	this.closed_y = null; // will be set to this.sprite.y upon open trigger
	this.open_direction = opensDown ? 1 : -1;

};
GO_SwitchGate.spriteImg = SDS_Load_Image("art/sheets/sprite/seagate.png");
GO_SwitchGate.spriteSheet = new TileSheet(4, 5, 1, 0, GO_SwitchGate.spriteImg);

GO_SwitchGate.prototype = new GameObject(
	new Sprite(
		GO_SwitchGate.spriteSheet,
		"Gate"
	),
	"Gate"
	);

	GO_SwitchGate.prototype.interactions = 0;

	GO_SwitchGate.prototype.Update = function(){
		this._heap.newopened = (this.opened && this.sticky) || (this.switch_current>=this.switch_total);
		if ((this._heap.newopened || this.jiggle) && this.closed_y==null){
			this.closed_y = this.sprite.y;
		}
		
		this.opened = this._heap.newopened;

		if ((this.opened || this.jiggle) && (this.sprite.y != this.closed_y+32*this.open_direction) ){
			this.sprite.move(0,this.open_direction);
		}
		else if (!this.opened && (this.closed_y!=null) && (this.sprite.y != this.closed_y) ){
			this.sprite.move(0,-this.open_direction);
		}

		if (this.jiggle) this.jiggle--;
		if (this.dejiggle) this.dejiggle--;
	}

	GO_SwitchGate.prototype.signal = function(sourceGO,direction){
		this.switch_current+=direction;
		if (direction>0 && !this.dejiggle){
			this.jiggle=2;
			this.dejiggle=(this.jiggle<<1)+1;
		}
	}
