-- write out that we loaded sucessfully (mor or less, anyway)
io.write("Starting script for Level5 in BlinkenLUA / ",_VERSION,"!\n")
bs.callback.engine.init("initLevel");


-- Required function: Initializing the level
function initLevel ()
    -- preload all gfx (on-the-fly loading is NOT recommended)
    GFX_DOOR_CLOSED = bs.gfx.load("fg_door_closed.bmp");
    GFX_DOOR_OPEN = bs.gfx.load("fg_door_open.bmp");
    GFX_SWITCH_RED = bs.gfx.load("fg_switch_red.bmp");
    GFX_SWITCH_GREEN = bs.gfx.load("fg_switch_green.bmp");
	

    -- create door and switch
	switchon = 0;
    OBJ_SWITCH = bs.obj.new(1*32, 5*32, GFX_SWITCH_RED, "visible");
    OBJ_DOOR = bs.obj.new(23*32, 7*32, GFX_DOOR_CLOSED, "visible,ontop,blocking");
	OBJ_SWITCH.callback.playeraction("handleDoorAction");
	
    -- load extra sound
    SND_DOOR_OPEN = bs.snd.load("fx_open_door.ogg");
    SND_DOOR_CLOSE = bs.snd.load("fx_open_door.ogg");

	-- Create elevator
	timer = 0;
	ELEVATOR_TIMER = 0;
	ELEVATOR_POS = 220;
	ELEVATOR_DIR = 1;
    GFX_ELEVATOR = {};    
    GFX_ELEVATOR[1] = bs.gfx.load("elevator2.bmp");
    GFX_ELEVATOR[2] = bs.gfx.load("elevator1.bmp");
    OBJ_ELEVATOR = bs.obj.new(43*32, 12*32, GFX_ELEVATOR[1], "blocking,visible,elevator");

	bs.callback.engine.physics("scriptPhysics");
end

-- Required function: Physics-loop for scripting part
function scriptPhysics ()
    if switchon == 1 then
        -- Block the door after a certain time
        timer = timer - 1;
        if timer == 0 then
            closeDoor();
        end
    end

	-- Elevator display
	ELEVATOR_TIMER = ELEVATOR_TIMER + 1;
	if ELEVATOR_TIMER == 50 then
		OBJ_ELEVATOR.gfx(GFX_ELEVATOR[2]);
	end
	if ELEVATOR_TIMER == 150 then
		OBJ_ELEVATOR.gfx(GFX_ELEVATOR[1]);
		ELEVATOR_TIMER = 0;
	end

	-- Elevator physics
	ELEVATOR_POS = ELEVATOR_POS + ELEVATOR_DIR;
	if ELEVATOR_POS == 64 or ELEVATOR_POS == 384 then
		ELEVATOR_DIR = ELEVATOR_DIR * -1;
	end

	OBJ_ELEVATOR.y(ELEVATOR_POS);	
end

-- Required function: Callback on "Action"-Button on FG-Objects
function handleDoorAction(obj_id)
    -- Open door if not open
    if switchon == 0 then
        openDoor();
    end
end

-- Script-internal functions
function openDoor()
    switchon = 1;

    -- exchange GFX for door and button
    OBJ_SWITCH.gfx(GFX_SWITCH_GREEN);
    OBJ_DOOR.gfx(GFX_DOOR_OPEN);

    -- make door nonblocking
    OBJ_DOOR.blocking(bs.no);
    timer = 500; -- 5 secs    

   -- play sound
   SND_DOOR_OPEN.play();
end

function closeDoor()
    switchon = 0;

    -- exchange GFX for door and button
    OBJ_SWITCH.gfx(GFX_SWITCH_RED);
    OBJ_DOOR.gfx(GFX_DOOR_CLOSED);

    -- Block the door again
    OBJ_DOOR.blocking(bs.yes);

   -- play sound
   SND_DOOR_CLOSE.play();
end
