-- DAWS Package file B / VehicleDamageStatus code

-- THANKS TO (cronological order):
	-- Rider (AMVI)
	-- Grimes (ED community)
	-- MBot (ED community)
	-- xcom (ED community)
	-- Ian (ED community)
	-- vicx (ED community)
	-- Pikey (ED community)
	-- ESAC_Matador (ED community)

-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################

	-- local function copy
	local base 						= _G
	local require 					= base.require
	local table 					= base.table
	local math 						= base.math
	local string					= base.string
	local pairs 					= base.pairs
	local ipairs 					= base.ipairs
	local print 					= base.print
	local io 						= base.io
	local lfs 						= base.lfs
	local os 						= base.os
	local zip 						= minizip
	local loadstring 				= base.loadstring
	--]]--
	
	-- common directory listing
	local mistdirectory 			= mistdirectoryDP -- lfs.currentdir() .. "AMVI/Common/Code/"
	local moddirectory 				= moddirectoryAE 	-- lfs.currentdir() .. "AMVI/AIEnhancement/"
	local debugdirectory  			= debugdirectoryAE	--lfs.currentdir() .. "AMVI/AIEnhancement/Debug/"
	local missionfilesdirectory 	= missionfilesdirectoryDP -- lfs.writedir() .. "Missions/"
	local logsdirectory				= logsdirectoryDP -- lfs.writedir() .. "Logs/"
	
	-- common export variables
	local exportfiletype 			= ".csv"
	--reportfiletype 				= ".doc"
	local configfiletype 			= ".csv"
	local tss 						= ";"
	
	local debugProcess				= false
	
	--improved random
	do
	   local oldrandom = math.random
	   local randomtable
	   math.random = function ()
		  if randomtable == nil then
			 randomtable = {}
			 for i = 1, 97 do
				randomtable[i] = oldrandom()
			 end
		  end
		  local x = oldrandom()
		  local i = 1 + math.floor(97*x)
		  x, randomtable[i] = randomtable[i], x
		  return x
	   end
	end	


-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################
-- ################################################################################################################################


	-- define effects table. If the random value stays below the threshold it will trigger the effect.
	local effectTable =	{
						[0.1] = "driverdead",
						[0.2] = "weaponbroken",
						[0.3] = "stopmove",							
						[0.6] = "moveaway",
						[0.95] = "suppression" -- in place
						}
	
	-- debug use
	local debughitcounter = 0			
	
	DAWS.hithandler = {}
	function DAWS.hithandler:onEvent(event)
		if event.id == world.event.S_EVENT_HIT then
			
			if debugProcess == true then
				env.info(("--> DAWS damage enhancer: hit event has been detected with a unit"))
				debughitcounter = debughitcounter +1
			end  
		
			--target
			local targetName = nil
			local targetTable = nil
			if event.target then
				targetName = event.target:getName()
				targetTable = Unit.getByName(targetName)
			end
			--shooter
			local shooterName = nil
			local shooterTable = nil
			if event.initiator then
				shooterName = event.initiator:getName()
				shooterTable = Unit.getByName(shooterName)
			end
			--weapon
			local weaponName = nil
			local weaponCat = nil
			local weaponFlag = nil		
			if event.weapon then
				weaponName = event.weapon:getTypeName()
				weaponCat = event.weapon:getCategory() -- http://wiki.hoggit.us/view/DCS_enum_weapon
			end
			
			-- reharse weapon info
			if debugProcess == true then
				env.info(("--> DAWS damage enhancer: hit properties are: Target = " .. tostring(targetName) .. ", Weapon = " .. tostring(weaponName) .. ", WeaponCat = " .. tostring(weaponCat)))
			end  
			
			-- define impact data & effects
			if targetTable then
				
				local effectfactor =  (math.floor(math.random()*100))/100
				if debugProcess == true then
					env.info(("--> DAWS damage enhancer: Found targetTable, effectfactor: " .. effectfactor ))
				end
				
				-- retrieve info 
				local targetDesc = targetTable:getDesc()
				
				if targetDesc and targetDesc.attributes["Ground Units"] == true then
					if targetTable:hasAttribute("Infantry") == nil or targetTable:hasAttribute("Infantry") == false then
						if debugProcess == true then
							env.info(("--> DAWS damage enhancer: unit is a ground vehicle, processing effectfactor"))
						end 	
						if SuperdebugProcess == true then
							DAWS.dumpTable(targetName .. ".lua", targetDesc)
						end						
						if debugProcess == true then
							env.info(("--> DAWS damage enhancer: target description retrieved" ))
						end
						
						-- apply modifiers
						
						-- if unit is heavy armored, apply 3X factor to hit effect resistance. If unit is non heavy armored but light armored, apply 1.2X factor to hit effect resistance
						if targetDesc.attributes.HeavyArmoredUnits and targetDesc.attributes.HeavyArmoredUnits == true then
							effectfactor = effectfactor*3
							if debugProcess == true then
								env.info(("--> DAWS damage enhancer: Target is armored, effectfactor modified to: " .. effectfactor ))
							end		
						elseif targetDesc.attributes.LightArmoredUnits and targetDesc.attributes.LightArmoredUnits == true then
							effectfactor = effectfactor*1.2
							if debugProcess == true then
								env.info(("--> DAWS damage enhancer: Target is light armored, effectfactor modified to: " .. effectfactor ))
							end							
						else
							if debugProcess == true then
								env.info(("--> DAWS damage enhancer: Target is not armored, effectfactor stays: " .. effectfactor ))
							end						
						end
		
						-- apply effects
						for val, effect in pairs(effectTable) do
						
							-- process suppression effect	
							if effect == "suppression" then
								if debugProcess == true then
									env.info(("--> DAWS damage enhancer: Evaluating suppression effect" ))
								end								
								if val > effectfactor then
									if debugProcess == true then
										env.info(("--> DAWS damage enhancer: effectfactor is < than suppression thereshold. Effect applied." ))
									end
									
									local targetgrouptable = targetTable:getGroup()
									if targetgrouptable then
										local targetgroupname = targetgrouptable:getName()
										if debugProcess == true then
											env.info(("--> DAWS damage enhancer: targetgrouptable for group " .. targetgroupname .. " exist" ))
										end								
										
										local targetgroupcontroller = targetgrouptable:getController()
										if targetgroupcontroller then
											if debugProcess == true then
												env.info(("--> DAWS damage enhancer: targetgroupcontroller exist" ))
											end
											
											targetgroupcontroller:setOption(0, 4)
											if debugProcess == true then
												env.info(("--> DAWS damage enhancer: " .. targetgroupname .. " has been suppressed" ))
											end										
											local reseteffect = function(targetgroupcontroller, targetgroupname)
												targetgroupcontroller:setOption(0, 0)
												if debugProcess == true then
													env.info(("--> DAWS damage enhancer: " .. targetgroupname .. " has been resetted, weapons free)" ))
												end	
											end
											
											local timerspread = math.floor(math.random()*30)
											local timerbase = 15
											local timerend = timerbase + timerspread
											timer.scheduleFunction(reseteffect, {targetgroupcontroller, targetgroupname}, base.timer.getTime() + timerend)
											
										end
									end
									
								else
									if debugProcess == true then
										env.info(("--> DAWS damage enhancer: effectfactor is > than suppression thereshold. Effect not applied" ))
									end							
								end
							end
							
							-- process dead unit effect	
							if effect == "driverdead" then
								if debugProcess == true then
									env.info(("--> DAWS damage enhancer: Evaluating driverdead effect" ))
								end								
								if val > effectfactor then
									if debugProcess == true then
										env.info(("--> DAWS damage enhancer: effectfactor is < than driverdead thereshold. Effect applied." ))
									end
																
									targetTable:getController():setOnOff(false)

								else
									if debugProcess == true then
										env.info(("--> DAWS damage enhancer: effectfactor is > than driverdead thereshold. Effect not applied" ))
									end							
								end
							end						

							-- process runaway unit effect	
							if effect == "driverdead" then
								if debugProcess == true then
									env.info(("--> DAWS damage enhancer: Evaluating driverdead effect" ))
								end								
								if val > effectfactor then
									if debugProcess == true then
										env.info(("--> DAWS damage enhancer: effectfactor is < than driverdead thereshold. Effect applied." ))
									end
																
									targetTable:getController():setOnOff(false)

								else
									if debugProcess == true then
										env.info(("--> DAWS damage enhancer: effectfactor is > than driverdead thereshold. Effect not applied" ))
									end							
								end
							end	


							
							-- other effect?!
							

						end
					else
						if debugProcess == true then
							env.info(("--> DAWS damage enhancer: unit is not a ground vehicle, effects not applied."))
						end
					end
				end
			else
				if debugProcess == true then
					env.info(("--> DAWS damage enhancer: No targetTable available"))
				end  				
			end
			--]]--

			if debugProcess == true then
				env.info(("--> DAWS damage enhancer: hitcounter =" .. debughitcounter))
			end  				
		
		end

	end
	world.addEventHandler(DAWS.hithandler)

	env.info(("DAWS AI Enhancement - VehicleDamageStatus pack loaded"))
	-- ~=
	
