--------------------------------------------------------------------------------
--  File     : qe_script.lua
--  Author(s): Якутин Сергей
--
--  Summary  : Главный управляющий скрипт QuestEngine.
--
--  Copyright © 2012 Floodlight Games.  All rights reserved.
--------------------------------------------------------------------------------
-- Переменные const
--------------------------------------------------------------------------------
STR_LOAD_SCREEN			= "Loading"
ENABLE_SERIALIZATION	= true
roomCommonResGroup 		= "RoomCommon"

-- states for YesNo dialog, where is show
DLG_STATE_MENU			= "menu"
DLG_STATE_SOLVE			= "solve"
--------------------------------------------------------------------------------
-- Общие функции
--------------------------------------------------------------------------------
-- Загрузка GUI ресурсов
function Create_GUI_LoadTask(folder_name)

	folder_prefix	= "gui:" .. folder_name .. "/"

	resource_dir		= folder_prefix .. "Images"
	if resm:IsDirExists(resource_dir) then
		resm:AddSpriteDirToTask	(resource_dir,	folder_name)
		resm:AddMaskDirToTask	(resource_dir,	folder_name)
	end

	resource_dir		= folder_prefix .. "Locale"
	if resm:IsDirExists(resource_dir) then
		resm:AddStringDirToTask	(resource_dir,	folder_name)
	end
	
	resource_dir		= folder_prefix .. "Video"
	if resm:IsDirExists(resource_dir) then
		resm:AddVideoDirToTask	(resource_dir,	folder_name)
	end
	
	resource_dir		= folder_prefix .. "ParticleGroups"
	if resm:IsDirExists(resource_dir) then
		resm:AddParticleGroupDirToTask	(resource_dir,	folder_name)
	end	
end
--------------------------------------------------------------------------------
-- Показ диалога YesNo
function Show_YN_Dialog(caption, state)
	local dlg_yesno = ui:GetDialog("DialogYesNo")
	dlg_yesno:SetUserTag(state)
	dlg_yesno:SetCaption(caption)
	dlg_yesno:Show()
end
-- Показ диалога Ok
function Show_OK_Dialog(caption, state)
	local dlg_ok = ui:GetDialog("DialogOk")
	dlg_ok:SetUserTag(state)
	dlg_ok:SetCaption(caption)
	dlg_ok:Show()
end
--------------------------------------------------------------------------------
-- Старт ИГРЫ - Let's go
--------------------------------------------------------------------------------
function GameStart(enable_serialization)
	ui:CloseDialog("Title")
	
	local Load_Dlg = ui:GetDialog(STR_LOAD_SCREEN)
	Load_Dlg:ControlTitleMusic("Curse_of_Wizard")
	
	if (qe:PlayGame("main_story.list", "GameChapter", not enable_serialization) == false) then
		if qe:GetStartGameResult() == qe.START_BadSave then
			Show_OK_Dialog("_Common:bad_saves", "bad_qe_save")
		elseif qe:GetStartGameResult() == qe.START_GameOver then		-- После GAME OVER перезапускаем игру
			GameStart(false)
		end
	end
end
--------------------------------------------------------------------------------
-- Не совместимый файл сохранения
--------------------------------------------------------------------------------
function OnIncompatibleSavedFile()
	Show_OK_Dialog("_Common:saves_incompatible", "incomp_chapter_save")
end
--------------------------------------------------------------------------------
function OnStartEngine()
	-- Первым делом Запуск музыки ;)
	music:Play("Curse_of_Wizard", true)

	--[ Создание списков на загрузку
	resm:AddCursorDirToTask			("cursors:",				"")
	
	--[ Loading screen
	Create_GUI_LoadTask(STR_LOAD_SCREEN)
	resm:LoadTasksAtOnce()
	
	ui:LoadAndCreateDialogs("gui:_system.agui")

	--[ Добавление заданий на загрузку общих ресурсов
	resm:AddSoundDirToTask			("sounds:",					"")
	resm:AddSoundDirToTask			("sounds:Room",				roomCommonResGroup)
	resm:AddFontDirToTask			("fonts:",					"")
	resm:AddSpriteDirToTask			("particles:Images",		"~Particles~")
	resm:AddParticleDirToTask		("particles:",				"")
	resm:AddParticleGroupDirToTask	("particles:",				"")

	--[ Добавление заданий на загрузку UI
	Create_GUI_LoadTask("_Common")
	Create_GUI_LoadTask("Options")
	Create_GUI_LoadTask("Profiles")
	Create_GUI_LoadTask("PersComment")
	Create_GUI_LoadTask("PersSpeakTop")
	Create_GUI_LoadTask("Title")
	Create_GUI_LoadTask("Journal")
	Create_GUI_LoadTask("GamePanel")
	Create_GUI_LoadTask("Solve")
	Create_GUI_LoadTask("PickItems")
	Create_GUI_LoadTask("IntroText")
	Create_GUI_LoadTask("GameMode")
	Create_GUI_LoadTask("Help")

	qe:StartLoading()
end

--------------------------------------------------------------------------------
function OnExitEngine()
end

--------------------------------------------------------------------------------
-- События загрузки общих ресурсов (инициированных qe:StartLoading())
--------------------------------------------------------------------------------
function OnStartLoadResources()
	ui:ShowDialog(STR_LOAD_SCREEN)
end

--------------------------------------------------------------------------------
function OnEndLoadResources()
	--ui:CloseDialog(STR_LOAD_SCREEN)
	ui:LoadAndCreateDialogs("gui:_game.agui")
	
	if gameini:IsFastStart() == true then
		ui:CloseDialog(STR_LOAD_SCREEN)
		if ui:GetDialog("DialogProfiles"):CheckDefaultProfile() == false then
			GameStart(ENABLE_SERIALIZATION)
		end
	else
		ui:GetDialog("DialogProfiles"):CheckDefaultProfile()
		ui:ShowDialog("Title")
	end

end

--------------------------------------------------------------------------------
-- Общеигровые события
--------------------------------------------------------------------------------
function OnStartChapter()
	ambient:Stop()
end

--------------------------------------------------------------------------------
function OnGameOver()
	qe:SaveGameToProfile()
	music:Play("Curse_of_Wizard", true)
	ui:ShowDialog("Title")
end

--------------------------------------------------------------------------------
function OnNextChapter()
	-- Авто-сохранение игры
	qe:SaveGameToProfile()
end

--------------------------------------------------------------------------------
function OnExitGame()
	music:Play("Curse_of_Wizard", true)
	ui:ShowDialog("Title")
end

--------------------------------------------------------------------------------
-- Обработка ГЛАВНОГО МЕНЮ
--------------------------------------------------------------------------------
function OnDialogEvent_Title(dialog, userAction)
	if userAction == dialog.STATE_ClickPlay then
		OnClickStartGame()
	elseif userAction == dialog.STATE_ClickProfiles then
		ui:ShowDialog("DialogProfiles")
	elseif userAction == dialog.STATE_ClickOptions then
		ui:ShowDialog("DialogOptions")
	elseif userAction == dialog.STATE_ClickHelp then
		ui:ShowDialog("Help")
	elseif userAction == dialog.STATE_ClickExit then
		Show_YN_Dialog("Title:exit_caption", DLG_STATE_MENU)
	end
end
--------------------------------------------------------------------------------
-- Обработка Стартового диалога
--------------------------------------------------------------------------------
function OnClickStartGame()
	local dialog = ui:GetDialog("Title")
	if dialog:IsCurProfileSavesExist() then
		local title = ui:GetDialog("Title")
		title:PlaySound("start_play")			-- продолжаем играть
		GameStart(ENABLE_SERIALIZATION)

		--dialog:PlaySound("menu_click")			-- eсли есть сохранения
		--ui:ShowDialog("StartDialog")				-- если нет профилей, то работать со стартовым диалогом
		
	else
		dialog:PlaySound("menu_click")				-- eсли нет сохранений
		dlg_gamemode = ui:GetDialog("GameMode")
		dlg_gamemode:SetUserTag("")
		dlg_gamemode:SetPosition(300, 200)
		dlg_gamemode:Show()
	end
end

function OnDialogClick_GameMode(dialog, widget)
	local title = ui:GetDialog("Title")
	if widget == "Ok" then
		if dialog:GetUserTag() == "InGameMenu" then
			if dialog:IsModeChange() then
				dialog:ApplyGameMode()
				ui:GetDialog("GamePanel"):OnChangeGameMode()
				ui:GetDialog("Solve"):OnChangeGameMode()
			end
			title:PlaySound("menu_click")
			dialog:Close()
		else
			dialog:ApplyGameMode()
			title:PlaySound("start_play")			-- продолжаем играть
			dialog:Close()
			GameStart(ENABLE_SERIALIZATION)
		end
	elseif widget == "Cancel" then
		dialog:Close()
	elseif widget == "btn_gmode0" then
		dialog:SelectMode(0)
	elseif widget == "btn_gmode1" then
		dialog:SelectMode(1)
	end
end

function OnDialogClick_StartDialog(dialog, widget)
	local title = ui:GetDialog("Title")
	if widget == "Continue" then
		title:PlaySound("start_play")			-- продолжаем играть
		dialog:Close()
		GameStart(ENABLE_SERIALIZATION)
	elseif widget == "NewGame" then
		local dlg_yesno = ui:GetDialog("StartDialogYesNo")
		dlg_yesno:SetCaption("Title:exit_caption")
		dlg_yesno:Show()
	elseif widget == "Cancel" then
		dialog:Close()
	end
end

function OnDialogClick_StartDialogYesNo(dialog, widget)
	if widget == "Yes" then
		dialog:Close()
		ui:ShowDialog("GameMode")		-- будет баг с тенью если поменять местами комманды
		ui:CloseDialog("StartDialog")
	elseif widget == "No" then
		dialog:Close()
	end
end
--------------------------------------------------------------------------------
-- Обработка диалога YesNo
--------------------------------------------------------------------------------
function OnDialogClick_DialogYesNo(dialog, widget)
	local state = dialog:GetUserTag()
	dialog:SetUserTag("")
	
	if widget == "Yes" then
		if state == DLG_STATE_MENU then
			qe:ExitEngine()
		elseif state == DLG_STATE_SOLVE then
			local dlg_solve = ui:GetDialog("Solve")
			dlg_solve:Solve()
			dlg_solve:Close()
			dialog:Close()
		end
	elseif widget == "No" then
		dialog:Close()
	end
end

--------------------------------------------------------------------------------
-- Обработка HELP
--------------------------------------------------------------------------------
function OnDialogClick_Help(dialog, widget)
	if widget == "Help_Close" then dialog:Close()
	end
end

--------------------------------------------------------------------------------
-- Обработка меню в игре
--------------------------------------------------------------------------------
function OnDialogClick_InGameMenu(dialog, widget)
	if widget == "igm_back" then dialog:Close()
	elseif widget == "igm_options" then ui:ShowDialog("DialogOptions")
	elseif widget == "igm_help" then ui:ShowDialog("Help")
	elseif widget == "igm_gamemode" then
		dlg_gamemode = ui:GetDialog("GameMode")
		dlg_gamemode:SetUserTag("InGameMenu")
		dlg_gamemode:SetPosition(400, 160)
		dlg_gamemode:Show()
	elseif widget == "igm_saveexit" then
		dialog:Close()
		if ENABLE_SERIALIZATION == true then qe:SaveGameToProfile()
		end
		qe:ExitGame()
	end
end

--------------------------------------------------------------------------------
-- Обработка ИГРОВОЙ ПАНЕЛИ
--------------------------------------------------------------------------------
function OnDialogEvent_GamePanel(dialog, userAction)
	if userAction == dialog.STATE_OnClickBookOpen or userAction == dialog.STATE_OnClickBookClose then
		ui:ShowDialog("Journal")
	elseif userAction == dialog.STATE_OnClickMenu then
		ui:ShowDialog("InGameMenu")
	end
end

--------------------------------------------------------------------------------
-- Обработка диалога создания нового профиля при ошибке загрузки профилей
--------------------------------------------------------------------------------
function OnDialogClose_DialogProfileNew(dialog)
	if ui:GetDialog("DialogProfiles"):GetProfileManResult() == true and gameini:IsFastStart() == true then
		GameStart(ENABLE_SERIALIZATION)
	end
end

--------------------------------------------------------------------------------
-- Обработка диалога профилей при ошибке загрузки профилей
--------------------------------------------------------------------------------
function OnDialogClose_DialogProfiles(dialog)
	if dialog:GetProfileManResult() == true and gameini:IsFastStart() == true then
		GameStart(ENABLE_SERIALIZATION)
	end
end

--------------------------------------------------------------------------------
-- Обработка Solve
--------------------------------------------------------------------------------
function OnDialogEvent_Solve(dialog, userAction)
	if userAction == 1 then
		Show_YN_Dialog("Solve:solve_confirm", DLG_STATE_SOLVE)
	end
end
--------------------------------------------------------------------------------
-- Обработка DialogOk при ошибке
--------------------------------------------------------------------------------
function OnDialogClick_DialogOk(dialog, widget)
	if widget == "Ok" then
		dialog:Close()
		local dlg_tag = dialog:GetUserTag()
		dialog:SetUserTag("")
		if dlg_tag == "bad_qe_save" then
			GameStart(false)
		elseif dlg_tag == "incomp_chapter_save" then
			qe:RestartCurrentChapter()
		end
	end
end
--------------------------------------------------------------------------------
-- Обработка Pause
--------------------------------------------------------------------------------
function OnDialogClick_Pause(dialog, widget)
	dialog:Close()
end
--------------------------------------------------------------------------------
-- Обработка Journal
--------------------------------------------------------------------------------
function OnDialogClick_Journal(dialog, widget)
	if widget == "Journal" then
		dialog:Close()
	end
end
--------------------------------------------------------------------------------
-- Обработка TitleScreen
--------------------------------------------------------------------------------
-- Работа с фоновыми звуками
function OnDialogShow_Title(dialog)
	ambient:Play("Gate")
end
function OnDialogClose_Title(dialog)
	ambient:Stop()
end
--------------------------------------------------------------------------------