quest = quest or {}

quest.g_LuaWatchFiles = true

quest.g_GameLua = nil

quest.run_exit_dialog = nil
function quest.OnClose()
    if not quest.run_exit_dialog then
        quest.run_exit_dialog = true
    else
        return false
    end
    local res = true
    if quest.g_GameLua then
        res = qe.OnClose(quest.g_GameLua)
    else
        local window = comics_window._self or main_menu.game_window
        if window then
            window.EndModal(1)
        end

--[[
        local window = comics_window._self or main_menu.game_window
        if not window then
            res = false
        else
                local modal_res = dialog_window.RunQuitDialog(window)
                if modal_res == 0 then
                    res = false
                else
                    window.EndModal(1)
                    res = true
                end
        end
]]

    end
    quest.close_flag = res
    quest.run_exit_dialog = nil
    return  res
end

function quest.PlayLevel(_resources, _window, _level, _scene_id, init, _load_file_name, _track, _go_silence)
	local result = -1
	
	qe.g_LuaThreadManager.Instance().Clear()
	
	assert(_level)
	if _scene_id==nil and _level.EnumScenes() ~= 0 then
		_scene_id = _level.GetScenes().Get().GetId()
	end
	
	if _scene_id then
		local cloned_level = _level.Clone()
		assert(cloned_level)

		local time_manager = sf.core.g_Application.GetTimeManager()
		local level_timer = sf.core.g_Application.GetTimeManager().AttachTimer("qe_level", sf.core.g_Application.GetTimeManager().GetTimer("main"))
		local script_timer = level_timer.AttachTimer("qe_script_timer")
		
		local game_lua = sf.lua.CLua("qe_level", quest.g_LuaWatchFiles)
        quest.g_GameLua = game_lua
		qe.g_LuaThreadManager.Instance().SetLua(game_lua)
		qe.g_LuaThreadManager.Instance().SetTimer(script_timer)
		if __QEBindGame then __QEBindGame(game_lua) end
		
		if init==nil then init = "" end


		result = qe.StartLevel(game_lua, _window, cloned_level, _scene_id, _resources, init, _load_file_name, _track, _go_silence)

		sf.core.g_Application.GetAudioManager().StopGroup("sound", 0)
		qe.g_LuaThreadManager.Instance().Clear()
		script_timer.Destroy()
		level_timer.Destroy()
		game_lua = nil
        quest.g_GameLua = nil
		collectgarbage()
	end
	
	return result
end
