-- animations  ----------------------------------------------------------------
dofile('data/Scripts/screens/Animations/MainMenu_anim_bg.lua')

-- Global variables ------------------------------------------------------------
mainMenu = nil
exitConfirmationScreen = nil

--------------------------------------------------------------------------------
class 'l_MainMenu' (BaseScreen)
--------------------------------------------------------------------------------
function l_MainMenu:__init(name, screen)
	BaseScreen.__init(self, name, screen)
	
	local cur_ambient = GetCurrentAmbientSoundTrackName()
	if cur_ambient ~= "" then
		StopAmbientSound(cur_ambient, true)
	end
	
	LoadSounds('data/Sound/MainMenu/')
	RegisterScenes()
	
	assert(not mainMenu)
	mainMenu = self
	self.buttonsActive = true
	
	-- animations -------------------------------------------------------------
	do
	    self.anim_bg = AnimationBundle(Loader_main_menu_Animations( self.screen:GetObject('bg_main_menu') ))
	    self.anim_bg:PlayAnimation('front')
	    
	    self.video_bg = CreateVideoEntity('data/Video/menu/main_menu.ogg', '', false)
        self.video_bg:AttachTo(self.screen:GetObject('bg_main_menu'))
        self.video_bg:SetZ(1)
        self.video_bg:SetScale(SCR_W/800)
        self.video_bg:SetXY(0, 0)
        self.video_bg:SetLoop(true)
        self.video_bg:PlayVideo()
        
        self.sound = MakeSoundEntity('MainMenu')
        self.sound:PlaySound(true)
    end
    
    self.sound_play_over = MakeSoundEntity('PlayOver')
    self.sound_play_over:AttachTo(screen)
	
	-- create buttons
	do
        self.bttn_play    = self:CreateButtonByName('Play')
        self.bttn_options = self:CreateButtonByName('Options')
        self.bttn_extras  = self:CreateButtonByName('Extras')
        self.bttn_exit    = self:CreateButtonByName('Exit')
        
        self.bttn_more_info = self:CreateButton('bttn_more_info')
        self.bttn_more_info:SetAction('OnMenuMoreInfoClick', self)
        self.bttn_more_info:SetActionSound("Menu_button_click")
        
        self.bttn_more_games = self:CreateButton('bttn_more_games')
        self.bttn_more_games:SetAction('OnMenuMoreGamesClick', self)
        self.bttn_more_games:SetActionSound("Menu_button_click")
        
        self.bttn_change_player = self:CreateButton('bttn_change_player')
        self.bttn_change_player:SetAction('OnMenuChangePlayerClick', self)
        self.bttn_change_player:SetActionSound("Menu_button_click")
        
        self.bttn_welcome = self:CreateButton('bttn_welcome')
        self.bttn_welcome:SetAction('OnMenuChangePlayerClick', self)
        self.bttn_welcome:SetActionSound("Menu_button_click")
    end
    
    do
        self.bttn_play:SetOpacity(0.01)
        self.anim_bg:PlayAnimation('bug')
        self.sound_play_over:PlaySound(true)
    end
    
	-- current profile name
	do
	    local text = CreateTextEntity(PLAYER_NAME_FONT, "")
		text:SetText('')
		text:AttachTo(screen)
		text:SetXY(230, 553)
		text:SetZ(190)
		text:SetTextAlignment(HGETEXT_CENTER + HGETEXT_MIDDLE)
		text:SetColor('0xFF050505')
		text:SetBorderSize(150, 0)
		text:SetAutoScale(true)
		text:SetAngle(-0.11)
		
		self.currentProfileNameText = text
	end
	
	if not IsCollectorsEdition() then
	    screen:GetObject('CE'):SetVisible(false)
	end
	
	
	if IS_SURVEY then
	    self.bttn_more_games:SetActive(false)
	    self.bttn_extras:SetActive(false)
    else
        screen:GetObject('layer_skull'):SetVisible(false)
	end
end
--------------------------------------------------------------------------------

function l_MainMenu:create_click_transition()
    if IsDebugMode() then
        --Console:Log('man_on_click')
    end
    
    local fadeTime = 1
	self.screen:GetObject('fade_area'):SetParam('0xFFFFFFFF', 0, true)
    self.screen:GetObject('fade_area'):ChangeOpacity(0, 1, fadeTime)
	
	self.timer:Add( function()
	                    self:StartGame()
                    end,
                    fadeTime)
end
--------------------------------------------------------------------------------

function l_MainMenu:OnBeforeDestroy()
end
--------------------------------------------------------------------------------

function l_MainMenu:OnUpdate(dt)
    self:UpdatePlayerWelcomeString()
end
--------------------------------------------------------------------------------

function l_MainMenu:UpdatePlayerWelcomeString()
    local bPlayerExist = GM:GetProfilesCount() > 0 and GM:GetCurrPlayer()
    
    if bPlayerExist then
	    local curentProfileName = GM:GetCurrPlayer().name
	    self.currentProfileNameText:SetScale(1)
	    self.currentProfileNameText:SetText(curentProfileName)
	end
	
	self:SetProfileNameVisible(bPlayerExist and self.buttonsActive)
end
--------------------------------------------------------------------------------
function l_MainMenu:SetProfileNameVisible(state)
    self.bttn_change_player:SetActive(state)
end
--------------------------------------------------------------------------------
function l_MainMenu:OnLostFocus()
end
--------------------------------------------------------------------------------
function l_MainMenu:OnGainFocus()
end
--------------------------------------------------------------------------------

function l_MainMenu:OnButtonMouseEnter(buttonName)
    if buttonName == 'OnPlayButtonClick' then
        self.bttn_play:SetOpacity(1)
        self.anim_bg:StopAnimation('bug')
        self.sound_play_over:StopSound()
    end
end
--------------------------------------------------------------------------------

function l_MainMenu:OnButtonMouseLeave(buttonName)
    if buttonName == 'OnPlayButtonClick' then
        self.bttn_play:SetOpacity(0.01)
        self.anim_bg:PlayAnimation('bug')
        self.sound_play_over:PlaySound(true)
    end
end
--------------------------------------------------------------------------------

function l_MainMenu.auxOnMainMenuScreenDestroy(screen)
	assert(screen and mainMenu)

    mainMenu:GetTopLevelScreen():Finish()
    mainMenu:GetTopLevelScreen():Destroy()
    mainMenu = nil
end

--------------------------------------------------------------------------------
function CreateMainMenu()
	local screen = CreateScriptedScreen('data/Scripts/screens/MainMenu.lua', 'l_MainMenu')
    PopUpScreensMgr:Push(screen, true, l_MainMenu.auxOnMainMenuScreenDestroy)
    screen:SetOpacity(0.8)

	local currentPlayer = GM:GetCurrPlayer()

	if GM.last_players_load_result_ == '' then
		if currentPlayer == nil then
			local delay = 0.5
	        GTimerDoString('CreateInputNameScreen(false)', delay)
		end
	else
		local promt_create_profile = true
        local corrupted_name
		if currentPlayer then
            local corrupted_name_delimeter_pos = string.find(GM.last_players_load_result_, ':')
            if corrupted_name_delimeter_pos then
                corrupted_name = string.sub(GM.last_players_load_result_, corrupted_name_delimeter_pos + 1)
                if currentPlayer.name ~= corrupted_name then
                    promt_create_profile = false
                end
            end
        end
		if promt_create_profile then
            local delay = 1
			mainMenu.timer:Add(function() CreateOKScreen(GetString('Q_ERROR_PROFILE_IS_CORRUPTED'), nil, false) end, delay / 2)
			if GM:GetPlayers():size() > 0 then
				mainMenu.timer:Add(function() CreateProfilesScreen() end, delay)
			else
				mainMenu.timer:Add(function() CreateInputNameScreen(false) end, delay)
			end
		else
		    local delay = 0.5
            local str_error = "'"..corrupted_name.."'\n "..GetString('Q_ERROR_PROFILE_IS_CORRUPTED_NOT_CURRENT')..'\n'
            mainMenu.timer:Add(function() CreateOKScreen(str_error, nil, false) end, delay)
		end
		GM.last_players_load_result_ = ''
	end
	
	if IsCollectorsEdition() then
		if currentPlayer then
			local state = currentPlayer.gameState
			if state then
			    local CE_OPENED_DIALOG_SHOWN_STATE      = 'CollectorsEditionOpenedDialogShown'
			    local CE_COMPLETED_DIALOG_SHOWN_STATE   = 'CollectorsEditionCompletedDialogShown'
			    if state:HasState(COLLECTORS_EDITION_OPENED, CE_TAG_NAME) and not state:HasState(CE_OPENED_DIALOG_SHOWN_STATE, CE_TAG_NAME) then
			        state:AddState(CE_OPENED_DIALOG_SHOWN_STATE, 'true', CE_TAG_NAME)
				    mainMenu.timer:Add(function() 
                                            CreateOKScreen(GetString('COLLECTORS_EDITION_OPENED_NOW'), nil, false)
                                       end, 0.4)
                elseif state:HasState(COLLECTORS_EDITION_COMPLETED, CE_TAG_NAME) and not state:HasState(CE_COMPLETED_DIALOG_SHOWN_STATE, CE_TAG_NAME) then
                    state:AddState(CE_COMPLETED_DIALOG_SHOWN_STATE, 'true', CE_TAG_NAME)
                    mainMenu.timer:Add(function() 
                                            CreateOKScreen(GetString('COLLECTORS_EDITION_COMPLETD_NOW'), nil, false)
                                       end, 0.4)
                end
			end -- if state then
		end
	end -- if IsCollectorsEdition() then
	
	if currentMusicTrack ~= 'music_2' then
	    PlayAmbientMusic('music_2', true)
    end
end
--------------------------------------------------------------------------------
function l_MainMenu:OnPlayButtonClick(ignore_complete)
	if not GM:GetCurrPlayer() then
		return
	end

	assert(mainMenu)
	
	self.bttn_play:SetOpacity(1)
	self.anim_bg:StopAnimation('bug')
    self.sound_play_over:StopSound()
	
	local state = GetGameManager():GetCurrPlayer().gameState
	if state:HasState(COMPLETE_QUEST) and ignore_complete then
	    local RestartGameProcessScreen = CreateYesNoScreen("RESTART_GAME_PROGRESS", "RestartGameYes", "RestartGameNo")
        PopUpScreensMgr:Push(RestartGameProcessScreen, false)
        return
	end
	
	if not state:HasState(PLAY_MODE) then 
	    CreatePlayingModeScreen(nil, true)
	else
	    -- stop buttons
	    self:StopButtons()
	    self:create_click_transition()
	end
end
--------------------------------------------------------------------------------

function l_MainMenu:StopButtons()
    self.buttonsActive = false
    
    self.bttn_play:SetActive(false)
    self.bttn_options:SetActive(false)
    self.bttn_extras:SetActive(false)
    self.bttn_more_info:SetActive(false)
    self.bttn_more_games:SetActive(false)
    self.bttn_exit:SetActive(false)
    self.bttn_welcome:SetActive(false)
    self.bttn_change_player:SetActive(false)
end
--------------------------------------------------------------------------------

function l_MainMenu:StartGame(tag)
    local state = GetGameManager():GetCurrPlayer().gameState
    
    self.sound:StopSound()
    PopUpScreensMgr:DestroyAll()
    StartGame(tag)
end
--------------------------------------------------------------------------------

function l_MainMenu:OnOptionsButtonClick()
	if not GM:GetCurrPlayer() then
		return
	end

    CreateOptionsScreen()
end
--------------------------------------------------------------------------------
function l_MainMenu:OnExitButtonClick()
	if not GM:GetCurrPlayer() then
		return
	end

    AppShouldExit()
end
--------------------------------------------------------------------------------
function l_MainMenu:OnMenuMoreInfoClick()
    if not GM:GetCurrPlayer() then
		return
	end
	
	CreateMoreInfoScreen()
end
--------------------------------------------------------------------------------

function l_MainMenu:OnMenuMoreGamesClick()
    if not GM:GetCurrPlayer() then
		return
	end
	
	CreateMoreGamesScreen()
end
--------------------------------------------------------------------------------

function l_MainMenu:OnExtrasButtonClick()
    if not GM:GetCurrPlayer() then
		return
	end

    if IsCollectorsEdition() then
        local state = GetGameManager():GetCurrPlayer().gameState
		if (state and state:HasState(COLLECTORS_EDITION_OPENED, CE_TAG_NAME) and  state:GetState(COLLECTORS_EDITION_OPENED, CE_TAG_NAME):HasValue('true')) or
		   (state and state:HasState(COLLECTORS_EDITION_COMPLETED, CE_TAG_NAME) and  state:GetState(COLLECTORS_EDITION_COMPLETED, CE_TAG_NAME):HasValue('true')) then
            CreateExtraScreen()
        else
		    CreateOKScreen(GetString('COLLECTORS_EDITION_CLOSED'), nil, false)
        end
    else
        CreateOKScreen(GetString('SE_CLICK_ON_EXTRAS'), nil, false)
    end
end
--------------------------------------------------------------------------------

function l_MainMenu:OnMenuChangePlayerClick()
    if not GM:GetCurrPlayer() then
		return
	end
	
	self:SetProfileNameVisible(false)
	CreateProfilesScreen()
end

--------------------------------------------------------------------------------
-- Exiting confirmation
--------------------------------------------------------------------------------
function AppShouldExit()
    if exitConfirmationScreen ~= nil then 
        return
    end
    
    exitConfirmationScreen = CreateYesNoScreen("REALLY_QUIT_GAME", "MenuExitConfirm", "MenuExitDiscard")
    PopUpScreensMgr:Push(exitConfirmationScreen, false)
end
--------------------------------------------------------------------------------
function MenuExitConfirm()
    exitConfirmationScreen = nil
    AppExit()
end
-------------------------------------------------------------------------------
function MenuExitDiscard()
    PopUpScreensMgr:Pop()
    exitConfirmationScreen = nil
end
-------------------------------------------------------------------------------
function GoToForumLink()
    if APP:IsFullScreen() then
        APP:Minimize()
    end

    APP:OpenUrlFromFile('data/Links/ForumURL.txt')
end

--------------------------------------------------------------------------------
function GoToStrategyGuideLink()
    if APP:IsFullScreen() then
        APP:Minimize()
    end

    APP:OpenUrlFromFile('data/Links/StrategyGuideURL.txt')
end
--------------------------------------------------------------------------------
function RestartGameYes()
    local state = GetGameManager():GetCurrPlayer().gameState
    state:Clear(DEFAULT_TAG_NAME)
	
	if not state:HasState(PLAY_MODE) then 
	    PopUpScreensMgr:Pop()
	
	    CreatePlayingModeScreen(nil, true)
	else
        PopUpScreensMgr:DestroyAll()
	    StartGame()
	end
end
-------------------------------------------------------------------------------
function RestartGameNo()
    PopUpScreensMgr:Pop()
end
-------------------------------------------------------------------------------


--------------------------------------------------------------------------------
-- CLEAR_ON_SAVE_BEGIN
-- Do not edit code listed below (generated by the editor on each save)
function l_MainMenu:LoadData(screen)
	local anim
	anim = CreateAnimation('data/Texture/Common/fade.png',0,0,512,384,1,0)
	anim:SetHotSpot(256,192)
	anim:SetBlendMode(2)
	anim:SetColor('0x00FFFFFF')
	screen:CreateObject('fade_area',anim,512,384,300,0,2,2)
	
	anim = CreateAnimation('data/Texture/Logo/CE.png',0,0,1024,104,1,0)
	anim:SetHotSpot(512,52)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFEEC385')
	screen:CreateObject('CE',anim,553,22,120,0,0.38,0.38)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_extras.png',0,0,224,120,3,0)
	anim:SetHotSpot(112,60)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_extras',anim,871,638,120,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_more_info.png',0,0,182,132,3,0)
	anim:SetHotSpot(91,66)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_more_info',anim,383,702,120,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_exit.png',0,0,150,148,3,0)
	anim:SetHotSpot(75,74)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_exit',anim,932,95,120,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_change_player.png',0,0,172,92,3,0)
	anim:SetHotSpot(86,46)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_change_player',anim,242,599,142,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_welcome.png',0,0,166,39,3,0)
	anim:SetHotSpot(83,19)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_welcome',anim,223,495,142,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_more_games.png',0,0,228,160,3,0)
	anim:SetHotSpot(114,80)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_more_games',anim,892,505,150,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_options.png',0,0,132,140,3,0)
	anim:SetHotSpot(66,70)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_options',anim,140,667,142,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/bttn/bttn_play.png',0,0,256,264,3,0)
	anim:SetHotSpot(128,132)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('bttn_play',anim,128,132,130,0,1,1)
	
	anim = CreateAnimation('data/Texture/Logo/GameLogo.png',0,0,314,184,1,0)
	anim:SetHotSpot(157,92)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('GameLogo',anim,693,142,120,0,1,1)
	
	anim = CreateAnimation('data/Texture/Menu/layers/layer_skull.png',0,0,336,372,1,0)
	anim:SetHotSpot(168,186)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('layer_skull',anim,856,583,200,0,1,1)
	
	anim = CreateAnimation('data/Texture/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('bg_main_menu',anim,512,384,100,0,1,1)
	
end
-- CLEAR_ON_SAVE_END
