--------------------------------------------------------------------------------
dofile('data/Lua/Constants.lua')
dofile('data/Lua/Utilities.lua')
dofile('data/Lua/Helpers.lua')
dofile('data/Lua/LevelHelpers.lua')
dofile('data/Lua/LevelDefaultEventHandlers.lua')
dofile('data/Lua/ReferenceCounter.lua')
dofile('data/Lua/Comics.lua')
dofile('data/Lua/screens/inventory.lua')
dofile('data/Lua/screens/menu.lua')
dofile('data/Lua/screens/Loading.lua')
dofile('data/scenes/01_Intro_Main.lua')
dofile('data/Lua/screens/ScreenManager.lua')
dofile('data/Lua/Sound.lua')
dofile('data/Lua/InteractiveHelp.lua')
dofile('data/Lua/Console.lua')
--------------------------------------------------------------------------------
levels = {};
levels[0] = ''
levels[10] = 'data/Scenes/01_Intro_Main.lua'
levels[20] = 'data/Scenes/02_Hotel_Reception_Main.lua'
levels[21] = 'data/Scenes/02_Hotel_Reception_HO.lua'
levels[30] = 'data/Scenes/03_Hotel_Camin_Hall_Main.lua'
levels[31] = 'data/Scenes/03_Hotel_Camin_Hall_HO.lua'
levels[40] = 'data/Scenes/04_Hotel_Street_Sunset_Main.lua'
levels[50] = 'data/Scenes/05_Metrodotel_Hall_Main.lua'
levels[51] = 'data/Scenes/05_Metrodotel_Hall_HO.lua'
levels[52] = 'data/Scenes/05_Metrodotel_Attic_HO.lua'
levels[60] = 'data/Scenes/06_Hotel_Street_Evening_Main.lua'
levels[70] = 'data/Scenes/07_Cemetry_Main.lua'
levels[71] = 'data/Scenes/07_Cemetry_HO.lua'
levels[72] = 'data/Scenes/07_Balkon_MG.lua'
levels[80] = 'data/Scenes/08_Library_Main.lua'
levels[81] = 'data/Scenes/08_Library_HO.lua'
levels[90] = 'data/Scenes/09_Museum_Street_Main.lua'
levels[91] = 'data/Scenes/09_Museum_Street_HO.lua'
levels[100] = 'data/Scenes/10_Museum_Hall_1_Main.lua'
levels[101] = 'data/Scenes/10_Museum_Hall_1_HO.lua'
levels[110] = 'data/Scenes/11_Museum_Hall_2_Main.lua'
levels[120] = 'data/Scenes/12_Theatre_Gate_Main.lua'
levels[130] = 'data/Scenes/13_Theatre_Fountain_Main.lua'
levels[131] = 'data/Scenes/13_Theatre_Fountain_HO.lua'
levels[132] = 'data/Scenes/13_Fountain_Minigame.lua'
levels[133] = 'data/Scenes/13_Theatre_Fountain_Zoom.lua'
levels[140] = 'data/Scenes/14_Workshop_Street_Main.lua'
levels[150] = 'data/Scenes/15_Theatre_Workshop_Inside_Main.lua'
levels[151] = 'data/Scenes/15_Theatre_Workshop_Inside_HO.lua'
levels[160] = 'data/Scenes/16_Theatre_Dead_End_Main.lua'
levels[161] = 'data/Scenes/16_Theatre_Dead_End_HO.lua'
levels[170] = 'data/Scenes/17_Theatre_Entrance_Main.lua'
levels[171] = 'data/Scenes/17_Theatre_Entrance_HO.lua'
levels[172] = 'data/Scenes/17_Ballance.lua'
levels[180] = 'data/Scenes/18_Theatre_Hall_Main.lua'
levels[181] = 'data/Scenes/18_Theatre_Hall_HO.lua'
levels[182] = 'data/Scenes/18_Balkon_MG.lua'
levels[190] = 'data/Scenes/19_Corridor_Main.lua'
levels[191] = 'data/Scenes/19_Corridor_MG.lua'
levels[200] = 'data/Scenes/20_Boiler_Room_Main.lua'
levels[201] = 'data/Scenes/20_Boiler_Room_HO.lua'
levels[210] = 'data/Scenes/21_Make_Up_Room_Main.lua'
levels[211] = 'data/Scenes/21_Make_Up_Room_HO1.lua'
levels[212] = 'data/Scenes/21_Make_Up_Room_HO2.lua'
levels[220] = 'data/Scenes/22_Backstage_Main.lua'
levels[221] = 'data/Scenes/22_Backstage_HO.lua'
levels[222] = 'data/Scenes/22_Rope.lua'
levels[240] = 'data/Scenes/24_Dolls_Main.lua'
levels[241] = 'data/Scenes/24_Dolls_HO.lua'
levels[242] = 'data/Scenes/24_Mosaic.lua'
levels[250] = 'data/Scenes/25_Balcony_Main.lua'
levels[251] = 'data/Scenes/25_Balcony_HO.lua'
levels[260] = 'data/Scenes/26_Backyard_Main.lua'
levels[261] = 'data/Scenes/26_Backyard_HO.lua'
levels[270] = 'data/Scenes/27_Master_Hall_Main.lua'
levels[271] = 'data/Scenes/27_Master_Hall_HO.lua'
levels[272] = 'data/Scenes/27_Pendulum_MG.lua'
levels[280] = 'data/Scenes/28_Master_Room_Main.lua'
levels[281] = 'data/Scenes/28_Runes_Lock.lua'
levels[290] = 'data/Scenes/29_Daughter_Room_Main.lua'
levels[291] = 'data/Scenes/29_Daughter_Room_HO.lua'
levels[292] = 'data/Scenes/29_picture.lua'
levels[300] = 'data/Scenes/30_Road_Fork_Main.lua'
levels[310] = 'data/Scenes/31_Draw_Well_Main.lua'
levels[320] = 'data/Scenes/32_Lift_Main.lua'
levels[321] = 'data/Scenes/32_Lift_HO.lua'
levels[322] = 'data/Scenes/32_Lift_MG.lua'
levels[330] = 'data/Scenes/33_Scene_Luk.lua'
levels[340] = 'data/Scenes/34_Prison_Cell.lua'
levels[350] = 'data/Scenes/35_Prison_Corridor_Main.lua'
levels[351] = 'data/Scenes/35_Prison_Corridor_HO.lua'
levels[355] = 'data/Scenes/35_Manipulator.lua'
levels[356] = 'data/Scenes/35_Numbers_MG.lua'
levels[360] = 'data/Scenes/36_Hell_System_Main.lua'
levels[361] = 'data/Scenes/36_Hell_System_HO.lua'
levels[362] = 'data/Scenes/36_Piano_MG.lua'
levels[363] = 'data/Scenes/36_Hell_System_MG.lua'
levels[370] = 'data/Scenes/37_Grot_Main.lua'
levels[371] = 'data/Scenes/37_Grot_HO.lua'
levels[380] = 'data/Scenes/38_Stairway.lua'
levels[390] = 'data/Scenes/39_Cemetery_Morning_Main.lua'
levels[400] = 'data/Scenes/40_Credits.lua'

--------------------------------------------------------------------------------
function sleep(aTime)

    local sleepStartTime = os.time();
    
    while (true) do
    
        if (os.time() - sleepStartTime > aTime)
        then
            break;
        end
        
    end
end
--------------------------------------------------------------------------------
ERS_LOGO_SCREEN = "ERS Logo Screen"
DISTRIBUTOR_LOGO_SCREEN = "Distributor Logo Screen"
TITLE_MOVIE_SCREEN = "Title Movie Screen"
LOADING_SCREEN = "Loading Screen"
INTRO_ONE_MOVIE_SCREEN = "Intro one screen"
TO_BE_CONTINUED_SCREEN = "To be continued screen"
--------------------------------------------------------------------------------

local date = os.date('*t')
math.randomseed(os.clock() + date.sec + date.min + date.hour + date.day + date.month + date.year)
--------------------------------------------------------------------------------
function PreloadSounds()

    LoadMusic("music1", "data/Music/fon_1.ogg");
	LoadMusic("music2", "data/Music/fon_2.ogg");
	LoadMusic("music3", "data/Music/fon_3.ogg");
	
	LoadMusic("logo", "data/sound/Logo.ogg");
	LoadMusic("loading", "data/sound/Logo_loop.ogg");
	LoadMusic("intro_kareta", "data/sound/intro_Kareta.ogg");

	LoadSound("03_spider_main", "data/Sound/spider_sitting_03.ogg");
	LoadSound("03_spider_click", "data/Sound/spider_running_03.ogg");
    LoadSound("wind", "data/Sound/wind.ogg");
	LoadSound("06_spider", "data/Sound/spider_running_06.ogg");
	LoadSound("12_spider", "data/Sound/spider_running_12.ogg");
	
	LoadSound("Menu_button_click", "data/Sound/Menu_button_click.ogg");
	LoadSound("Window_open", "data/Sound/Opening_window.ogg");

    LoadSound("Item_found", "data/Sound/item_found.ogg");
    LoadSound("Wrong_click", "data/Sound/Wrong_click.ogg");
    LoadSound("Cursor_change",  "data/Sound/Cursor_change.ogg");
	LoadSound("inventory_open", "data/Sound/inventory.ogg");
	LoadSound("hint", "data/Sound/hint.ogg");
	LoadSound("Curtains_up", "data/Sound/Curtains_up.ogg");
	LoadSound("Curtains_open", "data/Sound/Curtains_open.ogg");
	
	LoadSound("Fireplace", "data/Sound/Fireplace.ogg");
	
	LoadSound("piano", "data/Sound/piano.ogg");
	LoadSound("Lock", "data/Sound/Lock.ogg");
	LoadSound("Break_clock_glass", "data/Sound/Break_clock_glass.ogg");
	LoadSound("Garguel_wing", "data/Sound/Garguel_wing.ogg");
	LoadSound("Gates_opening", "data/Sound/Gates_opening.ogg");
	LoadSound("Door_opening", "data/Sound/Door_opening.ogg");
	
	LoadSound("Clock_opening_mechanism", "data/Sound/Clock_opening_mechanism.ogg");
	LoadSound("Lever", "data/Sound/Lever.ogg");
	LoadSound("Gears_working_loop", "data/Sound/Gears_working_loop.ogg");
	LoadSound("Bar_gate_opening", "data/Sound/Bar_gate_opening.ogg");
	LoadSound("Dresser_doors_opening", "data/Sound/Dresser_doors_opening.ogg");
	
	LoadSound("Ceiling_dust", "data/Sound/Ceiling_dust.ogg");
	LoadSound("Picture_fall_brake", "data/Sound/Picture_fall_brake.ogg");
	LoadSound("Violin_cemetery_door", "data/Sound/Violin_cemetery_door.ogg");
	
	LoadSound("MousePunish", "data/Sound/Common/Mouse_Punish.ogg");
	
end

--------------------------------------------------------------------------------
function GetLevelToLoad()
    --return levels[0]

   -- return levels[222]

    
  local state = GetGameManager():GetCurrPlayer().m_gameState
    if state:HasState('LastVisitedScene') then
        return state:GetState('LastVisitedScene'):Get(0)
    else
        return levels[10]
    end

end

--------------------------------------------------------------------------------
function GetFirstLevelPath()
    return 'data/Scenes/.lua'
end

--------------------------------------------------------------------------------
function DestroyCurrentLevel()

    if (play_field ~= nil)
    then
        OnSceneDestroy(play_field);
        play_field:GetLevelScreen():DestroySelf();
        play_field = nil;
    end

end

--------------------------------------------------------------------------------
function StartGame()

    local state = GetGameManager():GetCurrPlayer().m_gameState;
    
    if (state:HasState('IntroShown') and state:GetState('IntroShown'):HasValue('1'))
    then
        local level_to_load = GetLevelToLoad();
        load_level(level_to_load);
    else
    
        StopAmbientMusic(false);
    
        -- showing first intro
        state:AddState('IntroShown', '1');
        
        introscreen = CreateMovieScreen(INTRO_ONE_MOVIE_SCREEN);
        BuildIntro1MovieScreen();
        GM:SetCurrentScreen(introscreen);
        
        local music = CreateMusicEntity("intro_kareta");
        music:AttachTo(introscreen);
        music:Play(false);
    end
    
end

--------------------------------------------------------------------------------
function CleanUpGameResources()

    PopUpScreensMgr:DestroyAll();
    exitConfirmationScreen = nil;

    PlayAmbientMusic(nil);
    
    while(active_zones:GetTop())
    do
        active_zones:GetTop().SetVisible(false);
    end
    
    tutorScreen = nil;
    
    hidden_zoom_zones:PopAll();
    
    DestroyCurrentLevel();
    DragObject = nil;
    MiniGameField = nil;
    
    PendingIngameMenu = nil;
    
    GTimerClear();
    GTimerContinue();

end

--------------------------------------------------------------------------------
function StartTitleMovie()

    local fps = 12;
    local movieFramesCount = 34;
    local movieScreen = CreateMovieScreen(TITLE_MOVIE_SCREEN);
    local movieDuration = 34 / fps;
    movieScreen:SetDuration(movieDuration);
    
    local tw = 640;
    local th = 460;
    
    local sw = 1024;
    local sh = 768;
    
    local aspect = sw / tw;
    
    for i = 0, movieFramesCount - 1, 1
    do
        local d = math.floor(i / 10);
        local l = math.floor(i % 10);
        local texturePath = "data/Texture/Title movie/PSreel2_" .. d .. l .. ".jpg";
        
        local anim = movieScreen:CreateAnimation(texturePath);
        anim:SetHotSpot(tw / 2, th / 2);
        anim:SetPosXY(sw / 2, sh / 2);
        anim:SetScaleXY(aspect, aspect);
        
        local effector = CreateAnimationEffector();
        effector:AttachTo(anim);
        effector:SetLifeTime(i / fps, (i + 1) / fps);
        effector:Play();
    end
    
    local anim = movieScreen:CreateAnimation("data/Texture/Title movie/tm.png");
    anim:SetZ(5);
    anim:SetHotSpot(27, 17);
    anim:SetPosXY(898, 265);
    
    local effector = CreateAnimationEffector();
    effector:AttachTo(anim);
    effector:SetKey(_TRACK_O, 0, 0);
    effector:SetKey(_TRACK_O, 1.5, 0);
    effector:SetKey(_TRACK_O, 2.5, 1);
    effector:Play();
    
    GM:SetCurrentScreen(movieScreen);
    
    local music = CreateMusicEntity("logo");
    music:AttachTo(movieScreen);
    music:SetVolume(0.25);
    music:Play(false);

end

--------------------------------------------------------------------------------
function StartLoadingScreen()

    local loadingScreen = CreateLoadScreen(LOADING_SCREEN);
    BuildLoadingScreen(loadingScreen);
    GM:SetCurrentScreen(loadingScreen);
    
    local music = CreateMusicEntity("loading");
    music:AttachTo(loadingScreen);
    music:SetVolume(0.25);
    music:Play(false);

end

--------------------------------------------------------------------------------
function StartApplication()

    --StartLevel(GetLevelToLoad())

    ---[[
    local showIntro = true; -- debug
    if (showIntro)
    then
    
        local logoScreen = CreateLogoScreen(DISTRIBUTOR_LOGO_SCREEN);
        logoScreen:SetDuration(2.0);
        logoScreen:SetLogo("data/Texture/Logo/BigFishLogo.jpg");
        GM:SetCurrentScreen(logoScreen);
        
        --GetGameApp()->HideCursor();
        --StartLoadingScreen();
        --StartTitleMovie();
    else
        StartMainMenu();
        --StartTitleMovie();
	    --StartGame();
    end
    --]]

end

--------------------------------------------------------------------------------
function ScreenDidFinish(screen)

    if (exitingApp)
    then
        return;
    end

    local screenName = screen:GetName();
    if (screenName == DISTRIBUTOR_LOGO_SCREEN)
    then
        local logoScreen = CreateLogoScreen(ERS_LOGO_SCREEN);
        logoScreen:SetDuration(2.0);
        logoScreen:SetLogo("data/Texture/Logo/ERSLogo.jpg");
        GM:SetCurrentScreen(logoScreen);
        
        return;
    end
    
    if (screenName == ERS_LOGO_SCREEN)
    then 
        StartTitleMovie();
        return;
    end
    
    if (screenName == TITLE_MOVIE_SCREEN)
    then
        StartLoadingScreen();
        return;
    end
    
    if (screenName == LOADING_SCREEN)
    then
        StartMainMenu();
        return;
    end
    
    if (screenName == INTRO_ONE_MOVIE_SCREEN)
    then
        StartGame();
        return;
    end
    
    if (screenName == MOVIE_THEATRE_PLAY_23)
    then
    
    end
    
    if (mainMenu and PopUpScreensMgr:GetTop() == nil)
    then
        if (GM:GetCurrPlayer() == nil)
        then
            ShowInputPlayerNameScreen();
        else
            StartMainMenuContentScreen();
        end
    end
    
end

--------------------------------------------------------------------------------
function AppFocusLost()

    if play_field ~= nil
    then
        StartIngameMenu();
    end

end

--------------------------------------------------------------------------------
function AppFocusGain()

end

--------------------------------------------------------------------------------
function FullScreenChange()

    if (optionsScreen)
    then
        optionsScreen.fullscreenCheckbox:SetState(APP:IsFullScreen() and 1 or 0);
        SetFullscreen();
    end

end

--------------------------------------------------------------------------------
function ToBeContinued()

    TBCScreen = BuildOKScreen("TRIAL_COMPLETED", "EndTBCScreen")
    PopUpScreensMgr:Push(TBCScreen);
    
end

--------------------------------------------------------------------------------
function EndTBCScreen()

    TBCScreen = nil;
    CleanUpGameResources()

    StartMainMenu();
end

--------------------------------------------------------------------------------
function BuildYesNoScreen(message, yesCallback, noCallback)

    local zOffset = 50;
    local screen = CreateScreen();
    screen:SetName("YesNoScreen " .. message);
    screen:SetLayer(POPUP_WINDOWS_LAYER);
    local bg = screen:CreateAnimation("data/texture/GUI/YES_NO_Back.png"); -- 599, 473
    bg:SetHotSpot(298, 266);
    bg:SetPosXY(512, 384);
    bg:SetPosZ(0 + zOffset);
    
    local yesButton = MakeButton(459, 555, 100, 40);
    yesButton:SetSpriteUp("YesButton");
	yesButton:SetSpriteOver("YesButtonOver");
	yesButton:SetSpriteDown("YesButtonDown");
	yesButton:SetZ(1 + zOffset);
	--yesButton:GetCaption():SetScale(1.);
	
	yesButton:AttachTo(screen);
	yesButton:SetAction(yesCallback);
	yesButton:SetActionSound("Menu_button_click");
	--yesButton:SetTitle("Yes");
	
	local noButton = MakeButton(572, 555, 100, 40);
	noButton:SetZ(1 + zOffset);
	--noButton:GetCaption():SetScale(1.);
	
	noButton:AttachTo(screen);
	noButton:SetAction(noCallback);
	noButton:SetActionSound("Menu_button_click");
	noButton:SetSpriteUp("NoButton");
	noButton:SetSpriteOver("NoButtonOver");
	noButton:SetSpriteDown("NoButtonDown");
	--noButton:SetTitle("No");
	
	local textBox = CreateTextEntity(INGAME_MENU_FONT, message);
	--textBox:SetHotSpot(298, 206);
	textBox:SetXY(512, 314);
	textBox:SetZ(1 + zOffset);
	textBox:SetScale(1.0);
	textBox:SetRect(412, 264, 200, 100);
	textBox:AttachTo(screen);
    
    return screen;
    
end

--------------------------------------------------------------------------------
function BuildOKScreen(message, okCallback)

    local zOffset = 50;
    local screen = CreateScreen();
    screen:SetName("OKScreen " .. message);
    screen:SetLayer(POPUP_WINDOWS_LAYER);
    
    local bg = screen:CreateAnimation("data/Texture/GUI/Square_dialog_back.png");
    bg:SetHotSpot(298, 270);
    bg:SetPosXY(512, 350);
    bg:SetPosZ(0);
    bg:SetScaleXY(1, 1);
    bg:SetAngle(0);
    
    local okBG = screen:CreateAnimation("data/Texture/GUI/Button_center.png");
    okBG:SetHotSpot(135, 34);
    okBG:SetPosXY(512, 608);
    okBG:SetPosZ(1);
    okBG:SetScaleXY(1, 1);
    okBG:SetAngle(0);
    
    local OKButton = MakeButton(512, 610, 100, 40);
    OKButton:GetCaption():SetFont(BUTTONS_FONT);
	OKButton:GetCaption():SetScale(0.8);
	OKButton:SetZ(5 + zOffset);
	
	OKButton:AttachTo(screen);
	OKButton:SetAction(okCallback);
	OKButton:SetSpriteUp("OKButton");
	OKButton:SetSpriteOver("OKButtonOver");
	OKButton:SetSpriteDown("OKButtonDown");
	--OKButton:SetTitle("OK");
	OKButton:SetActionSound("Menu_button_click");
	
	local textBox = CreateTextEntity(INGAME_MENU_FONT, message);
	--textBox:SetHotSpot(298, 206);
	textBox:SetXY(512, 360);
	textBox:SetZ(1 + zOffset);
	textBox:SetScale(1.0);
	textBox:SetRect(412, 264, 200, 200);
	textBox:AttachTo(screen);
	textBox:SetTextAlignment(HGETEXT_CENTER + HGETEXT_MIDDLE);
	
	screen.textBox = textBox;
    
    return screen;
    
end

--------------------------------------------------------------------------------
function DisplayMessage(title, message, tag)

    if (CannotSwitchWindowedScreen)
    then
        return;
    end
    CannotSwitchWindowedScreen = 8;
    local callback = "PopCurrentPopUpScreen";
    if (tag == SYSTEM_MESSAGE_TAG_CANNOT_WINDOWED)
    then
        callback = "KillCannotSwitchWindowedScreen";
    end
    local scr = BuildOKScreen("EMPTY", callback);
    scr.textBox:SetText(message);
    scr.textBox:SetXY(512, 360 - 160);
    scr.textBox:SetBorderSize(520, 400);
    
    PopUpScreensMgr:Push(scr);


end

--------------------------------------------------------------------------------
function KillCannotSwitchWindowedScreen()

    CannotSwitchWindowedScreen = nil;
    PopCurrentPopUpScreen();
end