class 'MainMenuBase' (BaseScreen)

function MainMenuBase:__init(name)
	BaseScreen.__init(self, name)

	self:setupButtons()
	self:setupHotKeys()
	--self:checkProfiles()
	self:checkExtras()
	self:checkGameCompleted()

	if not isCollectorsEdition() then
		self:entityHide('CE')

		if self:hasEntityNamed('bttn_extras') then
			self:getEntityNamed('bttn_extras'):hide()
		end

		if self:hasEntityNamed('bttn_hidden_objects') then
			self:getEntityNamed('bttn_hidden_objects'):hide()
		end

		if self:hasEntityNamed('bttn_mini_games') then
			self:getEntityNamed('bttn_mini_games'):hide()
		end
	end
	
	if self:hasEntityNamed('bttn_options') then
	    if Application:getApplicationDescriptor().optionsMenuButtonEnabled == false then
	        self:entityHide('bttn_options')
	    end
	end


	if OS_IOS then
		if self:hasEntityNamed('bttn_exit') then
			self:entityHide('bttn_exit')
		end

		if self:hasEntityNamed('bttn_change_player') then
			self:entityHide('bttn_change_player')
		end


		self:checkProfiles()
		
		if self.updateScore then
			self:updateScore()
		end

		BFG.events.logMainMenuShown()
	end

end
-------------------------------------------------------------------------------

function MainMenuBase:__finalize()
end
-------------------------------------------------------------------------------

--[[
 * Метод создает таблицу для инициализации кнопок главного меню. Индексасия таблицы
 * ведется по имени кнопки. Шаблон описания кнопки:

	['bttn_name'] =
	{
		press   = bind(self.onNameButtonClick, self),   -- обработчик нажатия на кнопку
		sfx     = soundEntity,                          -- звуковой эффект нажатия на кнопку. По-умолчанию: getCommonSoundEntity('ButtonClick')
		bHide   = true                                  -- нужно ли при старте спрятать кнопку
	},

 * Любое из полей можно не задавать.
 * При добавлении новых кнопок в классе, расширяющий данный, нужно переопределить данный метод.
--]]
function MainMenuBase:createButtonsTable()
	local buttons = {
		['bttn_exit'] =
		{
			press = bind(self.onExitButtonClick, self)
		},
		['bttn_options'] =
		{
			press = bind(self.onOptionsButtonClick, self)
		},      
		['bttn_change_player'] =
		{
			press = bind(self.onChangePlayerButtonClick, self)
		},
		['bttn_help'] =
		{
			press = bind(self.onHelpButtonClick, self)
		},
		['bttn_play'] =
		{
			press = bind(self.onPlayButtonClick, self)
		},
		['bttn_more_info'] =
		{
			press = bind(self.onMoreInfoButtonClick, self)
		},
		['bttn_hidden_objects'] =
		{
			press = bind(self.onHiddenObjectsButtonClick, self)
		},
		['bttn_mini_games'] =
		{
		 	press = bind(self.onMiniGamesButtonClick, self)
		},
		-- ['bttn_more_games'] =
		-- {
		-- 	press = bind(self.onMoreGamesButtonClick, self)
		-- },
	}

	return buttons
end
-------------------------------------------------------------------------------

--[[
 * Инициализация кнопок главного меню.
--]]
function MainMenuBase:setupButtons()
	local buttons = self:createButtonsTable()

	for buttonName, info in pairs(buttons) do
		if self:hasEntityNamed(buttonName) then
			local button = self:getEntityNamed(buttonName)
			local sfx    = info.sfx or getCommonSoundEntity('ButtonClick')

			button:setSFXTrackOnPress( sfx )

			if info.press then
				button.onPress:add( info.press )
			end

			if info.bHide then
				button:hide()
			end
		end
	end
end
-------------------------------------------------------------------------------

function MainMenuBase:setupHotKeys()
	if isCheatMode() then
		self:getWindow():getHotkeySignal( Hotkey_Ctrl(ERSK_K) ):add(function()
																		completeSE()
																		self:checkGameCompleted()
																		ProfilesManager:save()
																	end)

		self:getWindow():getHotkeySignal( Hotkey_Ctrl(ERSK_L) ):add(function()
																		completeCE()
																		self:checkGameCompleted()
																		ProfilesManager:save()
																	end)
	end
end
-------------------------------------------------------------------------------

function MainMenuBase:checkProfiles()
	if OS_IOS then
		-- *** iOS profile management: only one profile ***
		current_player = ProfilesManager:getProfile('Player')
		if not current_player then
			current_player = ProfilesManager:addProfile('Player')
			current_player:getPreferences():setSoundVolume(0.7)
			current_player:getPreferences():setMusicVolume(0.7)

			ProfilesManager:setCurrentProfile(current_player)
			ProfilesManager:save()
		end
	else
		current_player = ProfilesManager:getCurrentProfile()
		local loadResult = ProfilesManager:getLastProfilesLoadResult()
		ProfilesManager:resetLastProfilesLoadResult()
		
		if loadResult == '' then
			if not current_player then
				createInputNameScreen(false)
			end
		else
			local delay = 0.5
			local promt_create_profile = true
			local corrupted_name
			if current_player then
				local corrupted_name_delimeter_pos = string.find(loadResult, ':')
				if corrupted_name_delimeter_pos then
					corrupted_name = string.sub(loadResult, corrupted_name_delimeter_pos + 1)
					if current_player.name ~= corrupted_name then
						promt_create_profile = false
					end
				end
			end
			if promt_create_profile then
				local callback = function()
					if ProfilesManager:getProfiles():size() > 0 then
						self.timer:add(function() createProfilesScreen() end, delay)
					else
						self.timer:add(function() createInputNameScreen(false) end, delay)
					end
				end
				createOkScreen(StringManager:getString('Q_ERROR_PROFILE_IS_CORRUPTED'), callback, false)
			else 
				local str_error = "'"..corrupted_name.."'\n "..GetString('Q_ERROR_PROFILE_IS_CORRUPTED_NOT_CURRENT')..'\n'
				createOkScreen(str_error, nil, false)
			end
		end
	end
end
-------------------------------------------------------------------------------
function MainMenuBase:onShown()
	if not OS_IOS then
		self.timer:add(	function()
						self:checkProfiles()
					end, 0.25)
	end
end
-------------------------------------------------------------------------------

--[[
 * Метод предназначен для проверки того, была ли последняя посещенная сцена запущена
 * для повторного прохождения. Если это так, то открывается соответственный скрин со
 * списком сцен для повторного прохождения. 
--]]
function MainMenuBase:checkExtras()
	if getPrimaryGameStateTag() == EGameStateTag.EXTRA then
		self.timer:add( function()
							setPrimaryGameStateTag( nil )

							local lastReplayedScene = ExtraContentHelpers.getLastReplayedScene()
							
							if lastReplayedScene then
								if isMinigameLevelType( lastReplayedScene ) then
									createExtraMiniGamesScreen()
								else
									createExtraHiddenObjectsScreen()
								end
							end
						end, 0)
	end
end
-------------------------------------------------------------------------------

--[[
 * Метод предназначен для проверки вывода соответствующих сообщения и прохождении SE и CE 
 * части игры. 
--]]
function MainMenuBase:checkGameCompleted()
	if isCollectorsEdition() then
		if current_player then
			local state = current_player.gameState
			local CE_OPENED_DIALOG_SHOWN_STATE		= 'CollectorsEditionOpenedDialogShown'
			local CE_COMPLETED_DIALOG_SHOWN_STATE	= 'CollectorsEditionCompletedDialogShown'
			if state:hasState(CE_OPENED, EGameStateTag.GENERAL) and not state:hasState(CE_OPENED_DIALOG_SHOWN_STATE, EGameStateTag.GENERAL) then
				state:addState(CE_OPENED_DIALOG_SHOWN_STATE, 'true', EGameStateTag.GENERAL)
				self.timer:add(	function() 
									createOkScreen(GetString('COLLECTORS_EDITION_OPENED_NOW'), nil, false)
								end, 0.4)
			elseif state:hasState(CE_COMPLETED, EGameStateTag.CE) and not state:hasState(CE_COMPLETED_DIALOG_SHOWN_STATE, EGameStateTag.GENERAL) then
				state:addState(CE_COMPLETED_DIALOG_SHOWN_STATE, 'true', EGameStateTag.GENERAL)
				self.timer:add(	function() 
									createOkScreen(GetString('COLLECTORS_EDITION_COMPLETD_NOW'), nil, false)
								end, 0.4)
			end
		end
	end
end

-------------------------------------------------------------------------------

function MainMenuBase:onUpdate(dt)
	local tf = self:getEntityNamed('textPlayerName')

	if current_player then
		tf:setVisible(true)
		tf:setText(current_player.name)
	else
		tf:setVisible(false)
	end
end
-------------------------------------------------------------------------------


--[[
 * Стандартные обработчики нажатия на кнопки в главном меню.
--]]
function MainMenuBase:onPlayButtonClick()
	if not current_player then
		return 
	end

	assert(not current_scene)

	local state = current_player.gameState
	local start =   function()
						PopUpScreensMgr:destroyAll()
						startGame(EGameStateTag.SE)
					end

	if state:hasState(SE_COMPLETED, EGameStateTag.SE) then
		createYesNoScreen("RESTART_GAME_PROGRESS", 	function()
														state:clear(EGameStateTag.SE)

														createPlayingModeScreen(function()
																					local msg = StringManager:getString('PLAY_MODE_CHANGE_NOTE')
																					createOkScreen(msg, start, false)
																				end)
													end, nil, false)
		return
	end

	
	if state:hasState(PLAY_MODE, EGameStateTag.SE) then
		start()
	else
		createPlayingModeScreen(function()
									local msg = StringManager:getString('PLAY_MODE_CHANGE_NOTE')
									createOkScreen(msg, start, false)
								end)
	end
end

-------------------------------------------------------------------------------

function MainMenuBase:onHelpButtonClick()
	if not current_player then
		return 
	end
	
	createHelpScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onMoreInfoButtonClick()
	if not current_player then
		return 
	end
	
	createMoreInfoScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onMoreGamesButtonClick()
    if not current_player then
		return 
	end
	createMoreGamesScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onExtrasButtonClick()
	if not current_player then
		return 
	end

	self:onMainMenuScreenDestroy()
	createExtraScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onChangePlayerButtonClick()
	if not current_player then
		return 
	end
	
	createProfilesScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onOptionsButtonClick()
	if not current_player then
		return 
	end
	
	createOptionsScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onHiddenObjectsButtonClick()
	if not current_player then
		return 
	end
	
	self:onMainMenuScreenDestroy()
	createExtraHiddenObjectsScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onMiniGamesButtonClick()
	if not current_player then
		return 
	end
	
	self:onMainMenuScreenDestroy()
	createExtraMiniGamesScreen()
end
-------------------------------------------------------------------------------

function MainMenuBase:onExitButtonClick()
	createYesNoScreen("REALLY_QUIT_GAME", bind(self.ApplicationExit, self), nil, false)
end
-------------------------------------------------------------------------------

function MainMenuBase:ApplicationExit()
	Application:getPlatform():exit()
end
-------------------------------------------------------------------------------

function MainMenuBase:onMainMenuScreenDestroy()
	PopUpScreensMgr:pop()
end
-------------------------------------------------------------------------------