quest_window = quest_window or {}
quest_window.actions = quest_window.actions or {}
quest_window.qwest_window_timer = sf.core.CTimerWrapper(sf.core.g_Application.GetTimeManager().GetTimer(_T("qe_level")).AttachTimer(_T("")))
quest_window.last_auto_save_time = 0
quest_window.auto_save_delay = 3000


quest_window.actions.menu_button = 
{
	pressed = function(_window) 
        quest_window.show_game_menu(_window)
	end
}

quest_window.actions.hint_button = 
{
	pressed = function()
        notepad.ingame_lua_widget.HideAfterCloseTutorial()
        profile.SetVariable("__hint_used", 1)
		level_hints.ShowHint()
	end
}

function quest.change_dif_level()
    quest_window.change_dif_level_flag = true
end

function quest.OnClose()
--[[
    local modal_res = dialog_window.RunQuitDialog(quest.global_quest_window)
    if modal_res == 1 then
        quest_window.SaveGame()
        quest.global_quest_window.EndModal(1)
        return true
    end
    return false
]]

    quest_window.SaveGame()
    quest.global_quest_window.EndModal(1)
    return true

end

function quest_window.Show(_objects, _window)
end

function quest_window.DoDraw(_this, _renderer)
    return true
end

function quest_window.Load(_this, _info, _templates)

end

function quest_window.DoUpdate(_this)
    if quest_window.minigame_hole_placeholder == nil then
        quest_window.minigame_hole_placeholder = _this.GetWidget("minigame_hole_placeholder", true).get()
        if not quest_window.minigame_hole_placeholder then 
            quest_window.minigame_hole_placeholder = false
        else
            quest_window.minigame_hole_placeholder.AddFlags(quest_window.minigame_hole_placeholder.FlagHidden)
            local color = sf.graphics.Color(quest_window.minigame_hole_placeholder.GetColor())
            color.Alpha = 255
            quest_window.minigame_hole_placeholder.SetColor(color)
        end
    end

    local current_time = quest_window.qwest_window_timer.Get().GetTime()    
    if current_time - quest_window.last_auto_save_time > quest_window.auto_save_delay and not threads_managment.IsClikThread() then
        quest_window.last_auto_save_time = current_time
        quest_window.SaveGame()
    end
    
    -- ачивка за прохождение игры на определенном уровне сложности
    if quest.g_LuaVariables.difficulty == nil then
        quest.g_LuaVariables.difficulty = difficulty.GetDifLevel()
    end
    if difficulty.GetDifLevel() ~= quest.g_LuaVariables.difficulty then
        achievements.OnDifficultyChanged()
    end
    
    if not quest_window._level_timer then 
        quest_window._level_timer = sf.core.g_Application.GetTimeManager().GetTimer("qe_level")
        __assert(quest_window._level_timer)
    end
    
    -- Ачивка За 4 часа игры без перерыва
    local profile = game.g_ProfileManager.Instance().GetCurrentProfile()
    if profile then
        local stats = profile.GetAchievementsStats()
       
        if not achievements.IsAchievementComplete("4_hours_of_game") then
            stats.GameTime = stats.GameTime + quest_window._level_timer.GetFrameDelta()
            if not quest_window._last_gametime or quest_window._last_gametime > stats.GameTime then 
                quest_window._last_gametime = stats.GameTime
            end
            if stats.GameTime - quest_window._last_gametime > 1000 then
                if stats.GameTime >= 4 * 60 * 60 * 1000 then
                    achievements.GetAchievement("4_hours_of_game")
                end
                quest_window._last_gametime = stats.GameTime
            end
        end
    end

    if quest_window.end_level_flag and quest_window.exit_to_main_menu == nil then
        _this.EndModal(2)
	else
		if quest.global_minigame_opened or notepad.window.visible then
			g_HintButtonWidget.AddFlags(g_HintButtonWidget.FlagDisabled)
		else
			g_HintButtonWidget.RemFlags(g_HintButtonWidget.FlagDisabled)
		end
        
        if quest.global_minigame_opened or notepad.window.visible or hidden_object.GetActiveScene() then
            additional_inventory.Disable()
        else
            additional_inventory.Enable()
        end
    end
end

function quest_window.OnChar(_this, _char, _keyboard_state, _state, _broadcast)
	return _this.SuperOnChar(_char, _keyboard_state, _state, _broadcast)
end

function quest_window.s10_finish_level()
    local current_profile = game.g_ProfileManager.Instance().GetCurrentProfile()
    if current_profile ~= nil then
        current_profile.SetLevelState(game.CProfile.LevelStateTypeFinished)
        game.g_ProfileManager.Instance().Save()
    end
end

function quest.OnStartLevel()
    sf.core.g_Application.GetAudioManager().SetGroupVolume("sound", 0)
    if g_GoSilenceInStartLevel then
        sf.core.g_Application.GetAudioManager().StopGroup("music", 0)
        sf.core.g_Application.GetAudioManager().SetGroupVolume("music", 0)
        sf.core.g_Application.GetAudioManager().Play(quest.start_track, -2, -2, -2, -2, -2);
    end
    end_level_lua_widget.StartLight(g_GoSilenceInStartLevel, quest_window.change_dif_level_flag)
end

function quest.OnCompleteLevel()
    quest_window.s10_finish_level()
    end_level_lua_widget.StartDark(quest.go_silence)
    quest_window.end_level_flag = true
    quest_window.change_dif_level_flag = true
end

function quest_window.SaveGame()
    local current_profile = game.g_ProfileManager.Instance().GetCurrentProfile()
    if current_profile ~= nil then
        local save_file_name = current_profile.GetSaveFileName()
        if current_profile.GetLevelState() ~= game.CProfile.LevelStateTypeFinished then
            current_profile.SetLevelState(game.CProfile.LevelStateTypeInGame)
        end
        game.g_ProfileManager.Instance().Save()
		game.g_Achievements.Instance().SaveProfilesAchievements()
        save_game.SaveLevelInfo(save_file_name)
    end
end

function quest_window.show_game_menu(_window)
    profile.SetVariable("ach_no_pause_2_chapters", -1)

    sf.core.g_Application.GetTimeManager().GetTimer(_T("qe_level")).SetK(0)
    local res = game_menu.Show(_window)
  
    sf.core.g_Application.GetTimeManager().GetTimer(_T("qe_level")).SetK(1)

    
    if res == 2 then
        difficulty.ApplyDifLevel()
        score.CalculateScore()
    end
    if res == 1 then
        -- выход в главное меню
        
        -- очищаем статисткику для некоторых ачивментов
        local current_profile = game.g_ProfileManager.Instance().GetCurrentProfile()
        __assert(current_profile)
        local stats = current_profile.GetAchievementsStats()
        stats.GameTime = 0
        
        quest_window.exit_to_main_menu = true
        quest_window.SaveGame()
        sf.core.g_Application.GetAudioManager().StopGroup("music", 0)
        sf.core.g_Application.GetAudioManager().StopGroup("sound", 0)
        sf.core.g_Application.GetAudioManager().StopGroup("voice", 0)
        _window.EndModal(1)
    end
end

function quest_window.OnKeyDown(_this, _key, _keyboard_state, _state, _broadcast)
	if _this.SuperOnKeyDown( _key, _keyboard_state, _state, _broadcast) then
        return true
    end
	
	if sf.core.g_Application.GetDebugLevel() >= sf.core.g_Application.DebugCheats then
		if _key == 115 then
	        threads_managment.InterruptClickScript()
	        return true
	    end

	    if _key == 116 then
	        quest.SetHints(quest.GetHints() + 1)
	        return true
	    end
		
	    if _key == 113 then
	        quest.ChangeAreaView()
	        return true
	    end

	    if _key == 114 then -- F3
	        if child_scenes.close_minigame(1) then
	            return true
			elseif hidden_object.CompleteUsingCheat() then
				return true
	        end
	        quest_window.s10_finish_level()
	        quest_window.end_level_flag = true
	        return true
	    end
	    if _key == 118 then
            cursor_lua_widget.show_cheat_hints = 1 - cursor_lua_widget.show_cheat_hints 
	        return true
	    end
	end
	
    return false
end

function quest_window.OnKeyUp(_this, _key, _keyboard_state, _state, _broadcast)
	return _this.SuperOnKeyUp( _key, _keyboard_state, _state, _broadcast)
end

function quest_window.OnMouseMove(_this, _pos, _state, _broadcast)
	local res = _this.SuperOnMouseMove( _pos, _state, _broadcast) 
	if sf.gui.g_Cursor.Instance().GetCursor()==sf.gui.CCursor.CursorPointer 
	and quest.global_minigame_opened and not quest.global_minigame_opened.GetPoly().IsContains(_pos.X, _pos.Y) 
    and __and(quest.global_minigame_opened.GetFlags(), sf.gui.CWidget.FlagHidden) == 0 then
		sf.gui.g_Cursor.Instance().SetCustomCursor(sf.core.g_Application.GetResourceManager().GetTexture("gui_cursors_pointer_stop"))
	end
	return res
end

function quest_window.OnMouseDown(_this, _pos, _button, _state, _broadcast)
	return _this.SuperOnMouseDown( _pos, _button, _state, _broadcast) 
end

function quest_window.OnMouseUp(_this, _pos, _button, _state, _broadcast)
	return _this.SuperOnMouseUp( _pos, _button, _state, _broadcast) 
end

function quest_window.OnDoubleClick(_this, _pos, _state, _broadcast)
	return _this.SuperOnDoubleClick( _pos, _state, _broadcast) 
end

function quest_window.OnMouseWheel(_this, _pos, _delta, _state, _broadcast)
	return _this.SuperOnMouseWheel( _pos, _delta, _state, _broadcast)
end

function quest_window.OnChildAction(_this, _action, _child)
	if not _child then return end
	local handler = quest_window.actions[_child.GetId().c_str()]
	if handler then handler = handler[_action.c_str()] end
	if handler then handler(_this, _child) end
end

function show_scene(_scene_id, _x, _y, _init_offset_x, _init_ffset_y)
    local current_scene_id = quest.global_current_main_scene.GetId().c_str()
    local current_track = g_SceneTrackMap[current_scene_id]    
    local new_track = g_SceneTrackMap[_scene_id]    
    if new_track ~= nil and new_track ~= current_track and new_track ~= "" and current_track ~= "" then
        sf.core.g_Application.GetAudioManager().StopGroup("music", 0)
        sf.core.g_Application.GetAudioManager().Play(new_track, -2, -2, -2, -2, -2);
    end
    child_scenes.show_scene(_scene_id, _x, _y, _init_offset_x, _init_ffset_y)
end

