"use strict";

// references a given function to adjust a room's water level up or down
var GO_WaterLevelMaintainer = function(valueFn,rate){
	this.sprite = new Sprite(null,"WaterLevelMaintainer");
	this.sprite.collision_flags = 0;
	this.sprite.setBoundingBox(0,0,1,1);
	this.sprite.game_object = this; // no longer a generic GO
	
	this.fn = valueFn ? valueFn : function(){return 0;};
	this.rate = rate ? Math.abs(rate) : 1;

	this.meli = null;
	this.meliFind=false; // she probably won't be in the map when we init; hopefully when we update
};

GO_WaterLevelMaintainer.prototype = new GameObject(
	new Sprite(
		null,
		"WaterLevelMaintainer"
	),
	"WaterLevelMaintainer"
	);

	GO_WaterLevelMaintainer.prototype.interactions = 0;

	GO_WaterLevelMaintainer.prototype.Update = function(){
		if (!this.meli && !this.meliFind){
			this.meli = this.manager.getNamedObject("Meli");
			this.meliFind = true;
		}

		if (this.sprite.map_room && this.sprite.map_room.water_layer){
			this._heap.targetLevel = this.fn();
			this._heap.newLevel = this.sprite.map_room.water_layer.surface_y;
			if (this._heap.newLevel < this._heap.targetLevel){
				this._heap.newLevel = Math.min(this._heap.newLevel+this.rate,this._heap.targetLevel);
			}
			if (this._heap.newLevel > this._heap.targetLevel){
				this._heap.newLevel = Math.max(this._heap.newLevel-this.rate,this._heap.targetLevel);
			}

			if (this.meli && 
				this.sprite.map_room.water_layer.surface_y>=this.meli.sprite.y+this.meli.sprite.box_top && 
				this.sprite.map_room.water_layer.surface_y<=this.meli.sprite.y+this.meli.sprite.box_bottom){
				
				this.meli.sprite.move(0,this._heap.newLevel - this.sprite.map_room.water_layer.surface_y);
			}

			this.sprite.map_room.water_layer.surface_y = this._heap.newLevel;

		}
	}