--================= KIỂM TRA ĐỘ KHÓ TRONG QUÁ TRÌNH CHƠI =================--
--Hiển thị biểu tượng độ khó ở góc trên bên phải của bảng Quest
--Có 5 cấp độ khó khăn: Dễ, Bình thường, Khó, Rất khó, Địa ngục
--Check độ khó và luôn trả về độ khó thấp nhất
--Nếu giảm độ khó trong quá trình chơi thì data DifficultyLevel sẽ giảm, KHÔNG hồi phục khi tăng độ khó lại
--==========================================================--

--[[
ZombieLore = {
        -- How fast zombies move. Default = Random
        -- 1 = Sprinters
        -- 2 = Fast Shamblers
        -- 3 = Shamblers
        -- 4 = Random
        Speed = 4,
        -- If Random Speed is enabled, this controls what percentage of zombies are Sprinters. Check the "Advanced" box below to use a custom percentage. Min: 0 Max: 100 Default: 0
        SprinterPercentage = 0,
        -- The damage zombies inflict per attack. Default = Normal
        -- 1 = Superhuman
        -- 2 = Normal
        -- 3 = Weak
        -- 4 = Random
        Strength = 2,
        -- The difficulty of killing a zombie. Default = Random
        -- 1 = Tough
        -- 2 = Normal
        -- 3 = Fragile
        -- 4 = Random
        Toughness = 4,
        -- How the Knox Virus spreads. Default = Blood and Saliva
        -- 1 = Blood and Saliva
        -- 2 = Saliva Only
        -- 3 = Everyone's Infected
        -- 4 = None
        Transmission = 1,
        -- How quickly the infection takes effect. Default = 2-3 Days
        -- 1 = Instant
        -- 2 = 0-30 Seconds
        -- 3 = 0-1 Minutes
        -- 4 = 0-12 Hours
        -- 5 = 2-3 Days
        -- 6 = 1-2 Weeks
        -- 7 = Never
        Mortality = 5,
        -- How quickly infected corpses rise as zombies. Default = 0-1 Minutes
        -- 1 = Instant
        -- 2 = 0-30 Seconds
        -- 3 = 0-1 Minutes
        -- 4 = 0-12 Hours
        -- 5 = 2-3 Days
        -- 6 = 1-2 Weeks
        Reanimate = 3,
        -- Zombie intelligence. Default = Basic Navigation
        -- 1 = Navigate and Use Doors
        -- 2 = Navigate
        -- 3 = Basic Navigation
        -- 4 = Random
        Cognition = 3,
        -- How often zombies can crawl under parked vehicles. Default = Often
        -- 1 = Crawlers Only
        -- 2 = Extremely Rare
        -- 3 = Rare
        -- 4 = Sometimes
        -- 5 = Often
        -- 6 = Very Often
        -- 7 = Always
        CrawlUnderVehicle = 5,
        -- How long zombies remember a player after seeing or hearing them. Default = Normal
        -- 1 = Long
        -- 2 = Normal
        -- 3 = Short
        -- 4 = None
        -- 5 = Random
        -- 6 = Random between Normal and None
        Memory = 2,
        -- Zombie vision radius. Default = Random between Normal and Poor
        -- 1 = Eagle
        -- 2 = Normal
        -- 3 = Poor
        -- 4 = Random
        -- 5 = Random between Normal and Poor
        Sight = 5,
        -- Zombie hearing radius. Default = Random between Normal and Poor
        -- 1 = Pinpoint
        -- 2 = Normal
        -- 3 = Poor
        -- 4 = Random
        -- 5 = Random between Normal and Poor
        Hearing = 5,
        -- Activates the new advanced stealth mechanics, which allows you to hide from zombies behind cars, takes traits and weather into account, and much more.
        SpottedLogic = true,
        -- If zombies that have not seen/heard player can attack doors and constructions while roaming.
        ThumpNoChasing = false,
        -- If zombies can destroy player constructions and defenses.
        ThumpOnConstruction = true,
        -- Whether zombies are more "active" during the day or night.  "Active" zombies will use the speed set in the "Speed" setting.  "Inactive" zombies will be slower, and tend not to give chase. Default = Both
        -- 1 = Both
        -- 2 = Night
        -- 3 = Day
        ActiveOnly = 1,
        -- If zombies trigger house alarms when breaking through windows or doors.
        TriggerHouseAlarm = false,
        -- If multiple attacking zombies can drag you down and kill you.  Dependent on zombie strength.
        ZombiesDragDown = true,
        -- If crawler zombies beside a player contribute to the chance of being dragged down and killed by a group of zombies.
        ZombiesCrawlersDragDown = false,
        -- If zombies have a chance to lunge at you after climbing over a fence or through a window if you're too close.
        ZombiesFenceLunge = true,
        -- Serves as a multiplier when determining the effectiveness of armor worn by zombies. Min: 0.00 Max: 100.00 Default: 2.00
        ZombiesArmorFactor = 2.0,
        -- The maximum defense percentage that any worn protective garments can provide to a zombie. Min: 0 Max: 100 Default: 85
        ZombiesMaxDefense = 85,
        -- Percentage chance of having a random attached weapon. Min: 0 Max: 100 Default: 6
        ChanceOfAttachedWeapon = 6,
        -- How much damage zombies take when falling from height. Min: 0.00 Max: 100.00 Default: 1.00
        ZombiesFallDamage = 1.0,
        -- Whether some dead-looking zombies will reanimate and attack the player. Default = World Zombies
        -- 1 = World Zombies
        -- 2 = World and Combat Zombies
        -- 3 = Never
        DisableFakeDead = 1,
        -- Zombies will not spawn where players spawn. Default = Inside the building and around it
        -- 1 = Inside the building and around it
        -- 2 = Inside the building
        -- 3 = Inside the room
        -- 4 = Zombies can spawn anywhere
        PlayerSpawnZombieRemoval = 1,
        -- How many zombies it takes to damage a tall fence. Min: -1 Max: 100 Default: 50
        FenceThumpersRequired = 50,
        -- How quickly zombies damage tall fences. Min: 0.01 Max: 100.00 Default: 1.00
        FenceDamageMultiplier = 1.0,
		
ZombieConfig = {
        -- Set by the "Zombie Count" population option, or by a custom number here. Insane = 2.5, Very High = 1.6, High = 1.2, Normal = 0.65, Low = 0.15, None = 0.0. Min: 0.00 Max: 4.00 Default: 0.65
        PopulationMultiplier = 0.65,
        -- A multiplier for the desired zombie population at the start of the game. Insane = 3.0, Very High = 2.0, High = 1.5, Normal = 1.0, Low = 0.5, None = 0.0. Min: 0.00 Max: 4.00 Default: 1.00
        PopulationStartMultiplier = 1.0,
        -- A multiplier for the desired zombie population on the peak day. Insane = 3.0, Very High = 2.0, High = 1.5, Normal = 1.0, Low = 0.5, None = 0.0. Min: 0.00 Max: 4.00 Default: 1.50
        PopulationPeakMultiplier = 1.5,
        -- The day when the population reaches its peak. Min: 1 Max: 365 Default: 28
        PopulationPeakDay = 28,
        -- The number of hours that must pass before zombies may respawn in a cell. If 0, spawning is disabled. Min: 0.00 Max: 8760.00 Default: 72.00
        RespawnHours = 72.0,
        -- The number of hours that a chunk must be unseen before zombies may respawn in it. Min: 0.00 Max: 8760.00 Default: 16.00
        RespawnUnseenHours = 16.0,
        -- The fraction of a cell's desired population that may respawn every RespawnHours. Min: 0.00 Max: 1.00 Default: 0.10
        RespawnMultiplier = 0.1,
        -- The number of hours that must pass before zombies migrate  to empty parts of the same cell. If 0, migration is disabled. Min: 0.00 Max: 8760.00 Default: 12.00
        RedistributeHours = 12.0,
        -- The distance a zombie will try to walk towards the last sound it heard. Min: 10 Max: 1000 Default: 100
        FollowSoundDistance = 100,
        -- The size of groups real zombies form when idle. 0 means zombies don't form groups. Groups don't form inside buildings or forest zones. Min: 0 Max: 1000 Default: 20
        RallyGroupSize = 20,
        -- The amount, as a percentage, that zombie groups can vary in size from the default (both larger and smaller).   For example, at 50% variance with a default group size of 20, groups will vary in size from 10-30. Min: 0 Max: 100 Default: 50
        RallyGroupSizeVariance = 50,
        -- The distance real zombies travel to form groups when idle. Min: 5 Max: 50 Default: 20
        RallyTravelDistance = 20,
        -- The distance between zombie groups. Min: 5 Max: 25 Default: 15
        RallyGroupSeparation = 15,
        -- How close members of a zombie group stay to the group's "leader". Min: 1 Max: 10 Default: 3
        RallyGroupRadius = 3,
        -- Min: 10 Max: 500 Default: 300
        ZombiesCountBeforeDelete = 300,
    },
		]]

require "vl_quest_globalmoddata"

local GetQuestGlobalModData = VLGMD.GetQuestGlobalModData

if not isClient() then	--SP and Server

	local zombieSettings = {}

	--Lấy các thiết lập của ZombieLore lúc ban đầu
	local function GetZombieSettings()
		local sandboxOptions = getSandboxOptions()
		zombieSettings.Speed = sandboxOptions:getOptionByName("ZombieLore.Speed"):getValue()
		zombieSettings.Cognition = sandboxOptions:getOptionByName("ZombieLore.Cognition"):getValue()
		zombieSettings.Memory = sandboxOptions:getOptionByName("ZombieLore.Memory"):getValue()
		zombieSettings.Sight = sandboxOptions:getOptionByName("ZombieLore.Sight"):getValue()
		zombieSettings.Hearing = sandboxOptions:getOptionByName("ZombieLore.Hearing"):getValue()
		zombieSettings.Strength = sandboxOptions:getOptionByName("ZombieLore.Strength"):getValue()
		zombieSettings.Toughness = sandboxOptions:getOptionByName("ZombieLore.Toughness"):getValue()
		zombieSettings.ActiveOnly = sandboxOptions:getOptionByName("ZombieLore.ActiveOnly"):getValue()
		zombieSettings.ZombiesArmorFactor = sandboxOptions:getOptionByName("ZombieLore.ZombiesArmorFactor"):getValue()
		zombieSettings.ZombiesMaxDefense = sandboxOptions:getOptionByName("ZombieLore.ZombiesMaxDefense"):getValue()
		zombieSettings.PlayerSpawnZombieRemoval = sandboxOptions:getOptionByName("ZombieLore.PlayerSpawnZombieRemoval"):getValue()
		
		zombieSettings.ZombiesDragDown = sandboxOptions:getOptionByName("ZombieLore.ZombiesDragDown"):getValue()
		zombieSettings.ZombiesCrawlersDragDown = sandboxOptions:getOptionByName("ZombieLore.ZombiesCrawlersDragDown"):getValue()
		zombieSettings.ZombiesFenceLunge = sandboxOptions:getOptionByName("ZombieLore.ZombiesFenceLunge"):getValue()
		
		zombieSettings.PopulationMultiplier = sandboxOptions:getOptionByName("ZombieConfig.PopulationMultiplier"):getValue()
		zombieSettings.PopulationStartMultiplier = sandboxOptions:getOptionByName("ZombieConfig.PopulationStartMultiplier"):getValue()
		zombieSettings.PopulationPeakMultiplier = sandboxOptions:getOptionByName("ZombieConfig.PopulationPeakMultiplier"):getValue()
		zombieSettings.PopulationPeakDay = sandboxOptions:getOptionByName("ZombieConfig.PopulationPeakDay"):getValue()
		zombieSettings.RespawnHours = sandboxOptions:getOptionByName("ZombieConfig.RespawnHours"):getValue()
		zombieSettings.RespawnUnseenHours = sandboxOptions:getOptionByName("ZombieConfig.RespawnUnseenHours"):getValue()
		zombieSettings.RespawnMultiplier = sandboxOptions:getOptionByName("ZombieConfig.RespawnMultiplier"):getValue()
		zombieSettings.RedistributeHours = sandboxOptions:getOptionByName("ZombieConfig.RedistributeHours"):getValue()
		zombieSettings.ZombiesCountBeforeDelete = sandboxOptions:getOptionByName("ZombieConfig.ZombiesCountBeforeDelete"):getValue()

		--for stat, val in pairs(zombieSettings) do
		--	print(stat, " - ", val)
		--end	
	end

	local function GetDifficultyLevel()
		GetZombieSettings()
		
		if zombieSettings.Speed == 3 then	--Shamblers
			--dễ
			return 1
		elseif	zombieSettings.Speed == 2 or zombieSettings.Speed == 4 then		--Fast Shamblers or Random
			--bình thường
			return 2
		elseif	zombieSettings.Speed == 1 then		--Sprinters
				--cực khó
			if zombieSettings.Cognition == 1 and zombieSettings.Memory == 1
				and zombieSettings.Sight == 1 and zombieSettings.Hearing == 1 
				and zombieSettings.Strength == 1 and zombieSettings.Toughness == 1 
				and zombieSettings.ActiveOnly == 1 
				--and zombieSettings.PlayerSpawnZombieRemoval == 4
				and zombieSettings.ZombiesArmorFactor >= 2 and zombieSettings.ZombiesMaxDefense >= 85
				and zombieSettings.ZombiesDragDown == true and zombieSettings.ZombiesCrawlersDragDown == true
				and zombieSettings.ZombiesFenceLunge == true 
				and zombieSettings.PopulationStartMultiplier >= 1 and zombieSettings.PopulationPeakMultiplier >= 1.5
				and zombieSettings.PopulationPeakDay <= 28 and zombieSettings.RespawnHours <= 72 
				and zombieSettings.RespawnUnseenHours <= 16 and zombieSettings.RespawnMultiplier >= 0.1 
				and zombieSettings.RedistributeHours <= 12 and zombieSettings.ZombiesCountBeforeDelete >= 300 then
				
				if zombieSettings.PopulationMultiplier >= 4 then
					--địa ngục
					return 5
				else
					--rất khó
					return 4
				end
			else
				--khó
				return 3
			end
		end
		
		return 1
	end

	--Check độ khó và luôn trả về độ khó thấp nhất
	--Nếu giảm độ khó trong quá trình chơi thì data DifficultyLevel sẽ giảm, KHÔNG hồi phục khi tăng độ khó lại
	local function SetDataDifficultyLevel()
		local dLevel = GetDifficultyLevel()
		
		local questMD = GetQuestGlobalModData()
		if not questMD.QData["DifficultyLevel"] then questMD.QData["DifficultyLevel"] = 999 end
		
		--Nếu DifficultyLevel khi check nhỏ hơn DifficultyLevel trước đó thì gán
		if dLevel < questMD.QData["DifficultyLevel"] then
			questMD.QData["DifficultyLevel"] = dLevel
			
			if isServer() then
				sendServerCommand("VL_DifficultyData", "SetData", {dLevel = dLevel})
			end
		end
	end

	if not isServer() then
		Events.OnGameStart.Add(SetDataDifficultyLevel)
	else
		Events.OnServerStarted.Add(SetDataDifficultyLevel)
	end

	Events.EveryHours.Remove(SetDataDifficultyLevel)
	Events.EveryHours.Add(SetDataDifficultyLevel)

end


if isClient() then

	--================= ONSERVERCOMMAND =================--
	VLOSC["VL_DifficultyData"] = VLOSC["VL_DifficultyData"] or {}

	VLOSC["VL_DifficultyData"]["SetData"] = function(args)	--{dLevel = dLevel}
		local questMD = GetQuestGlobalModData()
		if not questMD.QData["DifficultyLevel"] then questMD.QData["DifficultyLevel"] = 999 end
		
		questMD.QData["DifficultyLevel"] = args.dLevel	
	end

end