io.write("Water-Maker included!\n")

--
-- required files:
--  * water1.bmp - water6.bmp
--  * water_deep.bmp
--
-- todo: move_her(), drown() and dieDrowning() don't use any kind of "namespacing"
--
-- use with:
--  Water:new(x, y, is_surface);
--

Water = {
	gfx_surface = {
			[1] = bs.gfx.load("water1.png"),
			[2] = bs.gfx.load("water2.png"),
			[3] = bs.gfx.load("water3.png"),
			[4] = bs.gfx.load("water4.png"),
			[5] = bs.gfx.load("water5.png"),
			[6] = bs.gfx.load("water6.png")
	},
	gfx_deep=bs.gfx.load("water_deep.bmp"),
	obj_cnt = 0,
	drowning=0,
	drowntimer=bs.timer.new("dieDrowning",0.9),
	drowntimer_move_her_down=bs.timer.new("move_her",0.1)
};
function Water:new(x,y,is_surface)
    local obj = {};
    setmetatable(obj, self);
    self.__index = self;
    obj.is_surface=is_surface;
    if is_surface==1 then
        obj.animationFrame = 1;
        obj.fgobject = bs.obj.new((x-1)*32, (y-1)*32, obj.gfx_surface[obj.animationFrame], "visible,ontop");
        obj.fgobject.callback.playercollision("drown");
    else
        obj.fgobject=bs.obj.new((x-1)*32, (y-1)*32, obj.gfx_deep, "visible,ontop");
    end
    self.obj_cnt = self.obj_cnt + 1;
    self[self.obj_cnt] = obj;
end

bs.timer.new("WaterTimer", 0.1);

function move_her()
    if bs.player.speed_y()<0 and Water.drowning>0 then
        bs.player.speed_y(0);
    end
end
function WaterTimer ()
	for i = 1, Water.obj_cnt do
	        if Water[i].is_surface==1 then
		    Water[i].animationFrame = math.mod(Water[i].animationFrame, 6) + 1;
		    Water[i].fgobject.gfx(Water.gfx_surface[Water[i].animationFrame]);
		end
	end
end
function drown()
    if Water.drowning==0 then 
    	--play drowning sound
        Water.drowning=1;
	Water.drowntimer.active(bs.yes);
    end
end
function dieDrowning()
    --do action on second call
    if Water.drowning==2 then
        Water.drowntimer.active(bs.no);
	Water.drowning=0;
        bs.player.kill();
    end
    --skip first call that occurs immediately after calling Water.drowntimer.active(bs.yes)
    if Water.drowning==1 then
        Water.drowning=2;
    end
end
