require "ui_common"
require "fsm"
require "game"
require "hog_common"

local g_bInGame     = false
local g_CurCursor   = ""
local g_fsmUI       = FSM( {} )

local c_NumSaveGames = 7
-------------------------------------------------------------------------------
--  UI Finite State Machine description
-------------------------------------------------------------------------------
    
-------------------------------------------------------------------------------
-- "MainMenu" state is while staying in Main Menu
-------------------------------------------------------------------------------
g_fsmUI.MainMenu = 
{
    activity = function()
        call( "MainMenu", "show" )
        if (get( "menutrack", "playing" ) == "false" ) then
            call( "menutrack", "Play" )
            call( "gametracks", "Stop" )
        end
        g_bInGame = false
    end,
    -- transitions
    {
        event = "OnGame",
        state = "Game",
        action = function()   
            log( "OnGame" )
            g_bInGame = true
            call( "MainMenu", "close" )
            setLocation( "worldmap" )
        end
    },
    {
        event = "OnCredits",
        state = "Credits",
        action = function()
            showMainMenu( false )
        end
    },
    {
        event = "OnPlayers",
        state = "Players",
        action = function()
            showMainMenu( false )
        end            
    },
    {
        event = "OnOptions",
        state = "Options",
        action = function()
            showMainMenu( false )
        end             
    },
    {
        event = "OnExit", 
        state = "MainMenu",        
        action = function()
            if (messageBox( "txtSureToExit", "", "YesNo" ) == "Yes") then
				call( "game", "Quit" )
				g_fsmUI:setState( "Exit" )
			end
        end
    },
    {
        event = "OnBack", 
        state = "MainMenu",        
        action = function()
            if (messageBox( "txtSureToExit", "", "YesNo" ) == "Yes") then
				call( "game", "Quit" )
				g_fsmUI:setState( "Exit" )
			end
        end
    },
    {
        event = "OnDebug",  
        state = "Game",
        action = function()
            showMainMenu( false )
            m_bInGame = true
        end
    }
}

-------------------------------------------------------------------------------
-- "Game" state 
-------------------------------------------------------------------------------
g_fsmUI.Game = 
{
    activity = function()
    end,
    {
        state = "MainMenu",
        event = "OnMenu",
        guard = function()
            return (messageBox( "txtSureToExitGame", "", "YesNo" ) == "Yes")
        end,
        action = function()
            call( "ingamemenu", "close" )
        end
    },
    {
        event = "OnOptions",
        state = "Options",
        action = function()
            log( "OnOptions" )
        end          
    },
    {
        state = "Credits",
        event = "OnCredits",
        action = function()
            g_bInGame = false
            log( "OnCredits" )
        end
    }
}
    
-------------------------------------------------------------------------------
-- "Credits" state is while showing credits
-------------------------------------------------------------------------------
g_fsmUI.Credits = 
{
    activity = function()
        call( "CreditsDlg", "Show" )
    end,    
    -- transitions    
    {
        state = "MainMenu",
        event = "OnBack",
        action = function()
            call( "CreditsDlg", "Close" )
            call( "MainMenu", "show" )
        end
    }
}

-------------------------------------------------------------------------------    
-- "Options" state is an options screen
-------------------------------------------------------------------------------
g_fsmUI.Options = 
{
    activity = function()
        call( "OptionsDlg", "Show" )
    end,
    -- transitions
    {
        state = "MainMenu",
        event = "OnBack",
        guard = function()
            return not g_bInGame
        end,
        action = function()
            call( "OptionsDlg", "Close" )
            call( "GameSettings", "Save" )
            showMainMenu( true )
        end
    },
    {
        state = "Game",
        event = "OnBack",
        guard = function()
            return g_bInGame
        end,
        action = function()
            call( "OptionsDlg", "Close" )
            call( "GameSettings", "Save" )
        end
    }
}

-------------------------------------------------------------------------------
-- "Load" state is load screen
-------------------------------------------------------------------------------
g_fsmUI.Players = 
{
    activity = function()
        setCursorPos( 1000, 400 )
        showMainMenu( false )
        call( "PlayersDlg", "Show" )
    end,
    -- transitions
    {
        state = "MainMenu",
        event = "OnBack",
        guard = function()
            return not g_bInGame
        end,
        action = function()
            call( "PlayersDlg", "Close" )    
            showMainMenu( true )
        end
    }
}

-------------------------------------------------------------------------------
--  ui event dispatchers
-------------------------------------------------------------------------------
function sendEvent( event, item )
    --call( "sndClickButton", "Play" )
    log( "Event sent:" .. event )
    g_fsmUI:sendEvent( event, item )
end

function OnBack()       sendEvent( "OnBack"     )   end
function OnYes()        sendEvent( "OnYes"      )   end
function OnNo()         sendEvent( "OnNo"       )   end
function OnExit()       sendEvent( "OnExit"     )   end
function OnGame()       sendEvent( "OnGame"     )   end   

function OnPlayers()    
    set( "btnEditPlayerBack", "visible", true )
    sendEvent( "OnPlayers"  )   
end
   
function OnCredits()    sendEvent( "OnCredits"  )   end              
function OnOptions()    sendEvent( "OnOptions"  )   end       
function OnMenu()       sendEvent( "OnMenu"     )   end
function OnDebug()      sendEvent( "OnDebug"    )   end

function OnEscape() 
    OnBack()
end

--  create debug locations jump buttons
function onJumpToLocation( btn )
    local tag = tonumber( get( btn, "tag" ) )
    local objLocations = children( obj( "locations", "game" ) )
    local objLocation = objLocations[tag]
    local locName = get( objLocation, "name" )
    local objLocation = obj( locName, "game.locations" )
    call( obj( "mgscript", objLocation ), "play" )
    set( "LocationChanger", "location", locName )
    call( "anmChangeLocation", "Play" )
end

local dbgPanel = obj( "DebugPanel" )
local objLocations = children( obj( "locations", "game" ) )
local objBtn = obj( "BtnTemplate", dbgPanel )
local btnParent = parent( objBtn )

local idx = 1
for i, loc in ipairs( objLocations ) do
    local locName = get( loc, "name" )
    local newBtn = create( objBtn, "btn" .. locName, btnParent )
    set( newBtn, "text", locName )
    set( newBtn, "visible", true )
    set( newBtn, "tag", "" .. idx )
    idx = idx + 1
end
connectObjects( children( btnParent ), "unpress", "onJumpToLocation" );

function BuildPlayerList()
    local objListBox = obj( "playerlist" )
    local sList = ""
    local sCurPlayer = get( "GameSettings", "text" )
    local nEntries = 0
    local nSelected = 0
    for i = 0, c_NumSaveGames - 1 do
        local sPlayer = get( "game", "savegametext", i )
        if (sPlayer ~= "") then
            sList = sList .. "\"" .. sPlayer .. "\","
            if (sCurPlayer == sPlayer) then 
                nSelected = nEntries
            end
            nEntries = nEntries + 1
        end
    end
    set( objListBox, "strings", sList )
    set( objListBox, "SelectedItem", nSelected )
    if (nEntries == 0) then
        OnPlayers()
        set( "btnEditPlayerBack", "visible", false )
        call( "btnNewPlayer", "unpress" )
    end
end

function GetPlayerIndex( sPlayer )
    for i = 0, c_NumSaveGames - 1 do
        local sCurPlayer = get( "game", "savegametext", i )
        if (sPlayer == sCurPlayer) then
            return i
        end
    end
    return -1
end

function SaveGame()
    local sCurPlayer = get( "GameSettings", "text" )
    local nGameIdx = GetPlayerIndex( sCurPlayer )
    call( "game", "save", nGameIdx )
end

function SelectPlayer( sPlayer )
    local nGameIdx = GetPlayerIndex( sPlayer )
    if (nGameIdx == -1) then
        return
    end

    call( "game", "load", nGameIdx )
    set( "MainMenuPlayerName", "text", sPlayer )
    call( "InitWorldMap", "Play" )
    set( "GameSettings", "text", sPlayer )
    call( "GameSettings", "save" )
    call( "mainmenu", "show" )
    BuildPlayerList()
end

function OnSelectPlayer()
    local nPlayerIdx = tonumber( get( "playerlist", "SelectedItem" ) )
    local sPlayerName = get( children( obj( "playerlist" ) )[nPlayerIdx + 1], "text" )
    SelectPlayer( sPlayerName )
    log ("selected player " .. nPlayerIdx .. "(" .. sPlayerName .. ")" )
    OnBack()
end

function OnNewPlayer()
    local sPlayer = get( "playerNameEdit", "text" )
    if (sPlayer == "") then 
        messageBox( "txtPlayerNameEmpty", "", "OK" )
        return
    end
    if (GetPlayerIndex( sPlayer ) ~= -1) then
        messageBox( "txtPlayerExists", "", "OK" )
        return
    end
    local nIndex = GetPlayerIndex( "" )
    if (nIndex == -1) then
        messageBox( "txtNoMorePlayerSlots", "", "OK" )
        return  
    end
    local nNameLength = string.len( sPlayer )
    if nNameLength > 10 then
        messageBox( "txtMaxPlayerLenght", "", "OK" )
        return
    end
    set( "GameSettings", "text", sPlayer )
    call( "GameSettings", "save" )
    call( "ResetGame", "Play" )
    call( "game", "save", nIndex )

    call( "EditPlayer", "close" )
    
    set( "playerlist", "SelectedItem", GetPlayerIndex( sPlayer ) )
    BuildPlayerList()
end

function OnDeletePlayer()
    if (messageBox( "txtSureToDeletePlayer", "", "YesNo" ) == "No") then
        return
	end
    local nPlayerIdx = tonumber( get( "playerlist", "SelectedItem" ) )
    local sPlayerName = get( children( obj( "playerlist" ) )[nPlayerIdx + 1], "text" )
    local nGameIdx = GetPlayerIndex( sPlayerName )
    local sCurPlayer = get( "GameSettings", "text" )
    set( "GameSettings", "text", "" )
    call( "game", "save", nGameIdx )
    set( "GameSettings", "text", sCurPlayer )
    BuildPlayerList()
end

function RelaxModePressed()
    bRelaxMode = (get( "cbRelaxMode", "pressed" ) == "true")
    log( "RelaxMode " .. get( "cbRelaxMode", "pressed" ) )
    if (bRelaxMode) then 
        set( "GameSettings", "Tier", 1 )
    else
        set( "GameSettings", "Tier", 0 )
    end
end

-------------------------------------------------------------------------------
--  ui main FSM loop
-------------------------------------------------------------------------------
log( "Started UI State Machine." )
call( "GameSettings", "Load" )

local nRelaxMode = tonumber( get( "GameSettings", "tier" ) )
if (nRelaxMode == 0) then
    set( "cbRelaxMode", "pressed", false )
else
    set( "cbRelaxMode", "pressed", true )
end

call( "worldmapscript", "play" )

BuildPlayerList()
local sPlayerName = get( "GameSettings", "text" )
SelectPlayer( sPlayerName )

g_fsmUI:run( "MainMenu" )



          

