require "common"
require "ui_common"
require "levels"
require "hog_common"

-------------------------------------------------------------------------------
-- Constants
-------------------------------------------------------------------------------
local c_DTime = 0.05
local c_PulseAmplitude = 3.0
local c_PulseFrequency = 6.0
local c_ButtonFrame = 0
local c_ButtonFrameComplete = 1
-------------------------------------------------------------------------------
-- Setup
-------------------------------------------------------------------------------
local cTime = 0.0
local bInInventory = false
local bPaused = false
-------------------------------------------------------------------------------
-- Functions
-------------------------------------------------------------------------------
function GetLevel( sLocation )
    local tCurLevel = nil
    for i, lev in ipairs( g_Levels ) do
        if lev.level == sLocation then 
            tCurLevel = lev
        end
    end
    return tCurLevel
end

function GetCurLevel()
    return GetLevel( get( "variables.curlocation", "value" ) )   
end

function PlayStage( tStage )
    log( "PlayStage" )
    if (tStage == nil) then
        log( "trying to play nil stage" )
        setLocation( "worldmap" )
        return 
    end
    local sStageLocation = tStage.location
    log( "playing location " .. sStageLocation )
    local objLocation = obj( sStageLocation, "game.locations" )
    if (tStage.skin ~= nil) then
        set( obj( "skin", objLocation ), "value", tStage.skin )
    end
    log( "setting location " .. sStageLocation )
    setLocation( sStageLocation )
	call( "menutrack", "Stop" )
    call( "ComicsTrack", "Stop" )
    if (get("gametracks", "playing") == "false") then
        call( "gametracks", "Play" ) 
    end
    local objMgScript = obj( "mgscript", objLocation )
    call( objMgScript, "play" )
    wait( 0.5 )
    set( objMgScript, "paused", true )
    
    -- display task message box
    if (tStage.task ~= nil) then
        messageBox( tStage.task, "", "Play" )
    end
    set( objMgScript, "paused", false )
end

function OnInventory( button )
    local objStage = get( button, "text" )
    local tInvButtons = children( obj( "InventoryButtons" ) )
    local invIdx = getIndex( button, tInvButtons )
    for i, lev in ipairs( g_Levels ) do
        for j, stage in ipairs( lev.stages ) do
            if stage.inventory == invIdx then
                call( "inventory", "close" )
                bInInventory = true
                PlayStage( stage )
                return
            end
        end
    end
end

function OnPlay()
    call( "menutrack", "Stop" )
    local objButtons = obj( "location_buttons" )
    fade( 1.0, true )
    local tCurLevel = GetCurLevel()
    local nStages = #(tCurLevel.stages)    
    local curStage = GetLocationProgress( tCurLevel.level )
    log( "playing level: " .. tCurLevel.level .. " stage: " .. curStage )
    
    --  play comics
    if (curStage == 0) then
        PlayComics( tCurLevel.comics )
        curStage = 1
        SetLocationProgress( tCurLevel.level, curStage )
    end
    
    if (curStage > nStages) then 
        curStage = 1 
    end
    bInInventory = false
    PlayStage( tCurLevel.stages[curStage] )
end

function AllLevelsDone() 
    for i, lev in ipairs( g_Levels ) do
        local nStage = GetLocationProgress( lev.level )
        local nStages = #(lev.stages)  
        if nStage <= nStages then
            return false
        end
    end
    return true
end

function OnWin()
    log( "OnWin" )
    call( "sndWin", "play" )
	set ( "TutorialSwitch", "activeidx", "0" )
    if (bInInventory == true) then
        setLocation( "worldmap" )
        setCursor( "default" )
        return 
    end
    local objButtons = obj( "location_buttons" )
    local tCurLevel = GetCurLevel()
    local nStages = #(tCurLevel.stages)
    local objButton = obj( tCurLevel.level, objButtons )
    local nCurStage = GetLocationProgress( tCurLevel.level )
    nCurStage = nCurStage + 1
    SetLocationProgress( tCurLevel.level, nCurStage ) 
    log( "curLevel:" .. tCurLevel.level .. " curStage: " .. nCurStage .. " numStages: " .. nStages )
    if nCurStage > nStages then 
        if AllLevelsDone() then 
            PlayComics( "page_12" )
            call( "oncredits", "play" )
            call( "menutrack", "Play" )
            log("AllLevelsDone")
            return
        end
        setLocation( "worldmap" )
        SelectGoodLocation()
        call( "gametracks", "Stop" ) 
        call( "menutrack", "Play" )
    else
        OnPlay()
    end
    setCursor( "default" )
    OpenLocations()    
    call( "OnSaveGame", "play" )
end

function OnExitMinigame()
    setCursor( "default" )
    log( "OnExitMinigame" )
    if (messageBox( "txtSureToExitMiniGame", "", "YesNo" ) == "Yes") then 
        setCursor( "default" )
        call( "ingamemenu", "close" )
        setLocation( "worldmap" )
    end
end

function OpenLocations()
    local objButtons = obj( "location_buttons" )
    for i, lev in ipairs( g_Levels ) do
        local bOpen = true
        if lev.required ~= nil then
            for j, req in ipairs( lev.required ) do
                local nStage = GetLocationProgress( req )
                local nStages = #(GetLevel( req ).stages)    
                bOpen = bOpen and (nStage > nStages)
            end
        end
        
        local nStage = GetLocationProgress( lev.level )
        local nStages = #(lev.stages)  
        
        -- open inventory
        local tInvButtons = children( obj( "InventoryButtons" ) )
        setObjects( objInvButtons, "enabled", false )
        for j, stage in ipairs( lev.stages ) do
            if stage.inventory ~= nil and j < nStage then
                set( tInvButtons[stage.inventory], "enabled", "true" )
            end
        end
        
        local objButton = obj( lev.level, objButtons )
        if (nStage > nStages) then 
            set( objButton, "skinframe", c_ButtonFrameComplete )
            set( objButton, "enabled", false )
        else
            set( objButton, "skinframe", c_ButtonFrame )
        end
        local objButton = obj( lev.level, objButtons )
        set( objButton, "visible", bOpen )
    end
    set( "selection", "skinframe", -1 )
end

function OnLocationSelect( button )
    OpenLocations()
    
    if (get( button, "visible" ) == "false") then
        return false
    end

    local sLegend = get( obj( "legend", button ), "text" )
    local sLocation = get( obj( "location", button ), "text" )
    set( "LegendText", "text", sLegend )
    set( "curlocation", "value", sLocation )
    local objButtons = obj( "location_buttons" )
    local tButtons = children( objButtons )
    set( "thumbnail", "skinframe", getIndex( button, tButtons ) + 1 )
    
    local objSelectBtn = obj( "selection" )
    set( objSelectBtn, "skinframe", get( button, "skinframe" ) )
    set( objSelectBtn, "extents", get( button, "extents" ) )
    set( objSelectBtn, "tag", getIndex( button, tButtons ) )
    set( button, "skinframe", -1 )
    cTime = 0.0
    return true
end

function SelectGoodLocation()
    local objButtons = obj( "location_buttons" )
    for i, lev in ipairs( g_Levels ) do
        local nStage = GetLocationProgress( lev.level )
        local nStages = #(lev.stages)  
        local objButton = obj( lev.level, objButtons )
        if (nStage <= nStages) then
            if (OnLocationSelect( objButton ) == true) then
                return
            end
        end
    end
    OnLocationSelect( children( objButtons )[1] )
end

function InitWorldMap()
    local objButtons = obj( "location_buttons" )
    local tButtons = children( objButtons )
    connectObjects( tButtons, "onlbup", "OnLocationSelect" )
end

function ResetGame()
    log( "ResetGame" )
    call( "game", "startnewgame" )
    local objVars = obj( "variables.locations" )
    delObjects( children( objVars ) )
    InitWorldMap()
end

function StartWorldMap()
    log( "StartWorldMap" )
    --  play startup comics
    local objVarRoot = obj( "variables.locations" )
    if #(children( objVarRoot )) == 0 then
        PlayComics( "page_1" )
        call( "menutrack", "play" )
    end
    
    local objButtons = obj( "location_buttons" )
    local tButtons = children( objButtons )
    setObjects( tButtons, "visible", false )
    SelectGoodLocation() 
    setCursor( "default" )
end

function GetCurLocationObject()
    if (bInInventory) then
        local curLocation = tonumber( get( "game.locations", "activeidx" ) )
        return children( "game.locations" )[curLocation]
    end
    local tCurLevel = GetCurLevel()
    local nStages = #(tCurLevel.stages)    
    local curStage = GetLocationProgress( tCurLevel.level )
    if (curStage > nStages) then 
        curStage = 1 
    end
    local objLocation = obj( tCurLevel.stages[curStage].location, "game.locations" )
    return objLocation
end

function GetMGScript()
    return obj( "mgscript", GetCurLocationObject() )
end

function PauseGame( bPause )    
    if (bPause == nil or bPause == false) then
        log( "PauseGame: false" )
        bPause = false
    else
        log( "PauseGame: true" )
        bPause = true
    end
    
    if (bPaused == bPause) then
        return
    end 

    bPaused = bPause

    local objScript = GetMGScript()
    set( objScript, "paused", bPause )
    local objLocation = GetCurLocationObject()
    
    local objBtnPause = obj( "btnPause", objLocation )
    local objPanel = obj( "BlackoutPanel", objLocation )
    set( objPanel, "visible", bPause )
    call( "msgbox", "close" )
end

function UnpauseGame()
    PauseGame( false )
end

function TogglePause()
    PauseGame( not bPaused )
end

function InGameMenuClose()
    PauseGame( false )
    call( "ingamemenu", "Close" )
end

function OnInGameMenu()
    call( "ingamemenu", "show" )
    PauseGame( true )
end

function OnTutorial()
    call( "msgbox", "close" )
    PauseGame( true )
    call( "tutorialdlg", "show" )
end

function TutorialClose()
    PauseGame( false )
    call( "tutorialdlg", "Close" )
end

-------------------------------------------------------------------------------
-- Main loop
-------------------------------------------------------------------------------
InitWorldMap()
while true do
    local objSelectBtn = obj( "selection" )
    local nFrame = tonumber( get( objSelectBtn, "skinframe" ) )
    if (nFrame ~= -1) then
        local dX = c_PulseAmplitude*(1.0 + math.cos( math.pi + cTime*c_PulseFrequency ))
        assert( dX >= 0 )
        
        local nButton = tonumber( get( objSelectBtn, "tag" ) )
        local objButtons = obj( "location_buttons" )
        local tButtons = children( objButtons )
        local objButton = tButtons[nButton]
        local cX = tonumber( get( objButton, "left"   ) )
        local cY = tonumber( get( objButton, "top"    ) )
        local cW = tonumber( get( objButton, "width"  ) )
        local cH = tonumber( get( objButton, "height" ) )  
    
        local x = cX - dX
        local y = cY - dX
        local w = cW + dX*2.0
        local h = cH + dX*2.0
        local sExt = "" ..x .. "," .. y .. "," .. w .. "," .. h
        set( objSelectBtn, "extents", sExt )
    end
    wait( c_DTime )
    cTime = cTime + c_DTime
end
          

