--SPAWN NPC TRONG EVENT Survivalist_InHouse

require "vl_quest_utils"

VLF = VLF or {}

local Func = {}
Func.GetPlayerModData = VLF.GetPlayerModData
Func.GetStaticCoordOfBuilding = VLF.GetStaticCoordOfBuilding
Func.GetOutsideRoom = VLF.GetOutsideRoom

--Kiểm tra ModData của player về thời gian active lại event
local function CheckPlayerDataDelayEvent(player, args) --CheckPlayerDataForActiveEvent(player, {event = "Survivalist_InHouse", delayHour = 6})
	local pData = Func.GetPlayerModData({qStep = nil})
	if args.event == "Survivalist_InHouse" then
		--print("Client--------CheckPlayerDataForActiveEvent= ")
		if not pData.events.Survivalist_InHouse then
			return true
		elseif pData.events.Survivalist_InHouse and pData.events.Survivalist_InHouse.lastTime then
			local nowHour = getGameTime():getWorldAgeHours()
			local delayHour = args.delayHour or 6
			if (nowHour - pData.events.Survivalist_InHouse.lastTime) >= delayHour then
				return true
			--else
				--print("Client--------TIME PASSED= ", nowHour, pData.events.Survivalist_InHouse.lastTime, (nowHour - pData.events.Survivalist_InHouse.lastTime))
			end
		end
	end
	return false
end

--Set ModData player về thời gian delay event mới
local function SetPlayerDataDelayEvent(player, args) --SetPlayerDataDelayEvent(player, {event = "Survivalist_InHouse"})
	local pData = Func.GetPlayerModData({qStep = nil})
	if args.event == "Survivalist_InHouse" then
		if not pData.events.Survivalist_InHouse then pData.events.Survivalist_InHouse = {} end
		--print("Client--------SetPlayerDataDelayEvent= ")
		pData.events.Survivalist_InHouse.lastTime = getGameTime():getWorldAgeHours()
	end
end

--Client --Lấy buildings trong khoảng cách loading của player
local function GetBuildingsInRange(player, minDist, maxDist) --GetBuildingsInRange(player, 35, 60)
	local buildingList = getWorld():getMetaGrid():getBuildings()
	local bTab = {}
	for i=0, buildingList:size()-1 do
		local buildingDef = buildingList:get(i)
		if buildingDef then
			local x, y, z = Func.GetStaticCoordOfBuilding(buildingDef)
			local disX = math.abs(x - player:getX())
			local disY = math.abs(y - player:getY())
			--Lấy building nằm trong khoảng min max
			if ((disX >= minDist) and (disX <= maxDist)) and ((disY >= minDist) and (disY <= maxDist)) then
				local bSquare = getCell():getGridSquare(x, y, z)
				if bSquare then
					--Lấy IsoBuilding để gọi hàm buildingDef không chạy được
					local building = bSquare:getBuilding()
					if building then
						table.insert(bTab, building)
						--print("--------buildingDef= ", buildingDef)
					end
				end
			end
		end
	end
	return bTab
end

--Client --Kiểm tra square modData của building 
local function CheckBuildingModDataForActiveEvent(building, args) --CheckBuildingModDataForActiveEvent(building, {event = event, hoursToNextActive = hoursToNextActive})
	local buildingDef = building:getDef()
	if buildingDef then
		local x, y, z = Func.GetStaticCoordOfBuilding(buildingDef)
		local bSquare = getCell():getGridSquare(x, y, z)
		if bSquare then
			local sqData = bSquare:getModData()
			local event = args.event
			if event == "Survivalist_InHouse" then
				if not sqData.event_Survivalist_InHouse then
					--sendClientCommand(getPlayer(), 'NPCQuestCM', 'RequestEvents', {x = x, y = y, z = z, event = event, hoursToNextActive = args.hoursToNextActive})
					return true
				elseif sqData.event_Survivalist_InHouse and sqData.event_Survivalist_InHouse.lastActive then
					--print("Client----------CheckBuildingModDataForActiveEvent: 4444")
					local nowHour = getGameTime():getWorldAgeHours()
					if (nowHour - sqData.event_Survivalist_InHouse.lastActive) >= args.hoursToNextActive then
						return true
					end
				end
			end
		end
	end
	return false
end

local function ActiveEvent(building, args) ----ActiveEvent(building, {event = "Survivalist_InHouse", hoursToNextActive = 168})
	local player = getPlayer()
	if player and instanceof(player, "IsoPlayer") then
		local x, y, z = Func.GetStaticCoordOfBuilding(building:getDef())
		sendClientCommand(player, 'NPCQuestCM', 'RequestEvents', {x = x, y = y, z = z, event = args.event, hoursToNextActive = args.hoursToNextActive})
		SetPlayerDataDelayEvent(player, {event = args.event})
	end
end

--Client --Tính toán tỉ lệ xuất hiện Event Survivalist_InHouse
local function SpawnRate_Event_Survivalist_InHouse()
	local ageDay = getGameTime():getWorldAgeDaysSinceBegin()
	local rate
	if ageDay < 31 then rate = 100 --100/1000 = 10%
	elseif ageDay < 91 then rate = 70 --70/1000 = 7%
	else rate = 40 --40/1000 = 4%
	end
	return rate
end

--Client --check every hour
function VLF.Event_Survivalist_InHouse()
	local rate = SpawnRate_Event_Survivalist_InHouse()
	--local rate = 500
	local active = false
	local r = ZombRand(1000) --FIXME: ZombRand(1000)
	--print("Client-----Event_Survivalist_InHouse: random - ", r)
	if r < rate then
		active = true
	end
	if active == true then
		--kiểm tra player ModData đã reset cooldown chưa --thời gian tối thiểu cho cooldown event
		active = CheckPlayerDataDelayEvent(getPlayer(), {event = "Survivalist_InHouse", delayHour = 6}) --FIXME: 6
		--print("Client-----CheckPlayerDataDelayEvent: false IS IN COOLDOWN TIME - ", active)
	end
	
	if active == true then
		local player = getPlayer()
		local buildingList = GetBuildingsInRange(player, 27, 60) --FIXME: 27, 60
		for i = 1, 10 do
			--chọn ngẫu nhiên building
			local index = ZombRand(1, #buildingList + 1)
			local building = buildingList[index]
			--kiểm tra building ModData đã reset cooldown chưa
			if building and building:isResidential() and not building:hasRoom("office") and not building:hasRoom("elevator") then
				local outsideRoom = Func.GetOutsideRoom(building)
				if outsideRoom then
					local event, hoursToNextActive = "Survivalist_InHouse", 168 --FIXME: 168
					local activeEvent = CheckBuildingModDataForActiveEvent(building, {event = event, hoursToNextActive = hoursToNextActive})
					if activeEvent then
						ActiveEvent(building, {event = event, hoursToNextActive = hoursToNextActive})
						return
					end
				end
			else
				table.remove(buildingList, index)
			end
		end
	end
end
--Func.Event_Survivalist_InHouse = VLF.Event_Survivalist_InHouse
Events.EveryHours.Remove(VLF.Event_Survivalist_InHouse)
Events.EveryHours.Add(VLF.Event_Survivalist_InHouse)