SWEP.Base = "tacrp_base"
SWEP.Spawnable = true

AddCSLuaFile()

// names and stuff
SWEP.PrintName = "Infantry First Aid Kit"
SWEP.AbbrevName = "IFAK"
SWEP.Category = "[FT] Медицина"

SWEP.SubCatTier = "9Special"
SWEP.SubCatType = "9Special"

SWEP.Description = "Индивидуальная аптечка первой помощи. Содержит бинты, гемостаты и порошки QuikClot для остановки кровотечений."
SWEP.Description_Quote = "Поддержка жизни в полевых условиях."

SWEP.Trivia_Manufacturer = "Military Issue"
SWEP.Trivia_Year = "2000s"

SWEP.Faction = TacRP.FACTION_NEUTRAL
SWEP.Credits = "Original: Firearms Source 2\nPort: TacRP"

SWEP.ViewModel = "models/weapons/v_ifak.mdl"
SWEP.WorldModel = "models/Items/HealthKit.mdl"

SWEP.Slot = 4

SWEP.NoRanger = true
SWEP.NoStatBox = true

// handling

SWEP.MoveSpeedMult = 1
SWEP.ShootingSpeedMult = 1
SWEP.SightedSpeedMult = 1

SWEP.AimDownSightsTime = 0.25
SWEP.SprintToFireTime = 0.25

SWEP.Sway = 0
SWEP.FreeAimMaxAngle = 0

// hold types

SWEP.HoldType = "slam"
SWEP.HoldTypeSprint = "normal"
SWEP.HoldTypeBlindFire = false

SWEP.GestureShoot = ACT_HL2MP_GESTURE_RANGE_ATTACK_PISTOL
SWEP.GestureReload = ACT_HL2MP_GESTURE_RELOAD_PISTOL

SWEP.PassiveAng = Angle(0, 0, 0)
SWEP.PassivePos = Vector(0, -2, -4)

SWEP.BlindFireAng = Angle(0, 0, 0)
SWEP.BlindFirePos = Vector(0, 0, 0)

SWEP.SprintAng = Angle(0, 30, 0)
SWEP.SprintPos = Vector(2, 0, -12)

SWEP.SightAng = Angle(-0.5, 0, 0)
SWEP.SightPos = Vector(-3.412, -6.4, -2.238)

SWEP.CorrectivePos = Vector(0, 0, 0)
SWEP.CorrectiveAng = Angle(0, 0, 0)

SWEP.HolsterVisible = true
SWEP.HolsterSlot = TacRP.HOLSTER_SLOT_GEAR
SWEP.HolsterPos = Vector(2, 0, 0)
SWEP.HolsterAng = Angle(-90, 0, 0)

// reload

SWEP.ClipSize = -1
SWEP.Ammo = "none"

// sounds

SWEP.Sounds = {}
SWEP.Sounds["bandage"] = {
    {time = 0.4, sound = "FAS2_Bandage.Retrieve"},
    {time = 1.25, sound = "FAS2_Bandage.Open"},
    {time = 2.15, sound = "FAS2_Hemostat.Retrieve"}
}

SWEP.Sounds["quikclot"] = {
    {time = 0.3, sound = "FAS2_QuikClot.Retrieve"},
    {time = 1.45, sound = "FAS2_QuikClot.Loosen"},
    {time = 2.55, sound = "FAS2_QuikClot.Open"}
}

SWEP.Sounds["suture"] = {
    {time = 0.3, sound = "FAS2_Hemostat.Retrieve"},
    {time = 3.5, sound = "FAS2_Hemostat.Close"}
}

// attachments

SWEP.Attachments = {
    [1] = {
        PrintName = "Аксессуар",
        Category = "acc",
        AttachSound = "TacRP/weapons/flashlight_on.wav",
        DetachSound = "TacRP/weapons/flashlight_off.wav",
    },
}

SWEP.FreeAim = false
SWEP.Scope = false

SWEP.DrawCrosshair = true
SWEP.DrawCrosshairInSprint = true

// Custom vars
SWEP.EasterWait = 0

function SWEP:Initialize()
	self:SetHoldType(self.HoldType)
	
	if CLIENT then
		self.SoundTime = 0
		self.SoundEntry = 1
		self.CurrentSoundTable = nil
	end
end

function SWEP:Deploy()
	local owner = self:GetOwner()
	if SERVER and IsValid(owner) then
		owner:GiveAmmo(4, "Bandages", true)
		owner:GiveAmmo(3, "Quikclots", true)
		owner:GiveAmmo(2, "Hemostats", true)
	end
	
	return true
end

function SWEP:Holster()
	if self.HealTime and CurTime() < self.HealTime then
		return false
	end
	
	if CLIENT then
		self.CurrentSoundTable = nil
		self.SoundEntry = 1
		self.SoundTime = 0
	end
	
	return true
end
local Mins, Maxs = Vector(-8, -8, -8), Vector(8, 8, 8)

function SWEP:FindHealTarget()
	local owner = self:GetOwner()
	if not IsValid(owner) then return owner end
	
	local tr = util.TraceHull({
		start = owner:GetShootPos(),
		endpos = owner:GetShootPos() + owner:GetAimVector() * 50,
		filter = owner,
		mins = Mins,
		maxs = Maxs
	})
	
	if tr.Hit and IsValid(tr.Entity) and tr.Entity:IsPlayer() then
		return tr.Entity
	end
	
	return owner
end

function SWEP:PlaySounds(soundTable)
	if not self.Sounds[soundTable] then return end
	
	self.CurrentSoundTable = soundTable
	self.SoundEntry = 1
	self.SoundTime = CurTime()
end

function SWEP:Think()
	local CT = CurTime()
	
	-- Sound system
	if CLIENT and self.CurrentSoundTable then
		local sounds = self.Sounds[self.CurrentSoundTable]
		if sounds and sounds[self.SoundEntry] then
			local snd = sounds[self.SoundEntry]
			if CT >= self.SoundTime + snd.time then
				self:EmitSound(snd.sound, 70, 100)
				
				if sounds[self.SoundEntry + 1] then
					self.SoundEntry = self.SoundEntry + 1
				else
					self.CurrentSoundTable = nil
					self.SoundEntry = 1
				end
			end
		end
	end
	
	-- Healing process
	if self.CurrentHeal and CT >= self.HealTime then
		self:EndHealingProcess()
	end
	
	-- Update viewmodel bodygroups
	if CLIENT and not self.CurrentHeal then
		self:UpdateBodygroups()
	end
end

function SWEP:UpdateBodygroups()
	local owner = self:GetOwner()
	if not IsValid(owner) then return end
	
	local vm = owner:GetViewModel()
	if not IsValid(vm) then return end
	
	-- Bodygroup 2 - бинты (0-2)
	vm:SetBodygroup(2, math.Clamp(owner:GetAmmoCount("Bandages"), 0, 2))
	
	-- Bodygroup 3 - гемостаты/квикклоты
	local hemostats = owner:GetAmmoCount("Hemostats")
	
	if hemostats > 0 then
		vm:SetBodygroup(3, hemostats == 1 and 2 or 3)
	else
		local quikclots = owner:GetAmmoCount("Quikclots")
		vm:SetBodygroup(3, quikclots > 0 and 1 or 0)
	end
end

function SWEP:EndHealingProcess()
	local owner = self:GetOwner()
	if not IsValid(owner) then return end
	
	-- Play end animation
	local vm = owner:GetViewModel()
	if IsValid(vm) then
		local anim = "idle"
		if self.CurrentHeal == "suture" and owner:GetAmmoCount("Hemostats") == 1 then
			anim = "bandage_end"
		else
			anim = self.CurrentHeal .. "_end"
		end
		
		local seq = vm:LookupSequence(anim)
		if seq > 0 then
			vm:SendViewModelMatchingSequence(seq)
		end
	end
	
	owner:RemoveAmmo(1, self.AmmoType)
	
	if CLIENT then
		self:UpdateBodygroups()
	end
	
	if SERVER then
		if self.OwnHeal then
			owner:SetHealth(math.Clamp(owner:Health() + self.HealAmount, 0, owner:GetMaxHealth()))
		else
			if IsValid(self.Target) then
				self.Target:SetHealth(math.Clamp(self.Target:Health() + self.HealAmount, 0, self.Target:GetMaxHealth()))
			end
		end
	end
	
	self.CurrentHeal = nil
	self.HealTime = nil
	self.HealAmount = nil
	self.Target = nil
	self.OwnHeal = false
end

function SWEP:PrimaryAttack()
	if not IsFirstTimePredicted() then return end
	
	local owner = self:GetOwner()
	if not IsValid(owner) then return end
	
	local bandages = owner:GetAmmoCount("Bandages")
	if bandages <= 0 then return end
	
	local target = self:FindHealTarget()
	if not IsValid(target) then return end
	
	-- Проверка здоровья
	if CLIENT then
		if target:Health() >= 100 then return end
	else
		if target:Health() >= target:GetMaxHealth() then return end
	end
	
	local CT = CurTime()
	
	self:SetNextPrimaryFire(CT + 2.95)
	self:SetNextSecondaryFire(CT + 2.95)
	self.HealTime = CT + 2.5
	self.CurrentHeal = "bandage"
	self.AmmoType = "Bandages"
	self.HealAmount = 10
	self.Target = target
	self.OwnHeal = (target == owner)
	
	-- Анимация
	local vm = owner:GetViewModel()
	if IsValid(vm) then
		local seq = vm:LookupSequence("bandage")
		if seq > 0 then
			vm:SendViewModelMatchingSequence(seq)
		end
	end
	
	-- Звуки
	self:PlaySounds("bandage")
	
	return true
end

function SWEP:SecondaryAttack()
	if not IsFirstTimePredicted() then return end
	
	local owner = self:GetOwner()
	if not IsValid(owner) then return end
	
	local hemostats = owner:GetAmmoCount("Hemostats")
	local quikclots = owner:GetAmmoCount("Quikclots")
	
	if hemostats <= 0 and quikclots <= 0 then return end
	
	local target = self:FindHealTarget()
	if not IsValid(target) then return end
	
	-- Проверка здоровья
	if CLIENT then
		if target:Health() >= 100 then return end
	else
		if target:Health() >= target:GetMaxHealth() then return end
	end
	
	local CT = CurTime()
	
	if hemostats > 0 then
		-- Гемостат
		self:SetNextPrimaryFire(CT + 5.5)
		self:SetNextSecondaryFire(CT + 5.5)
		self.HealTime = CT + 4.5
		self.CurrentHeal = "suture"
		self.AmmoType = "Hemostats"
		self.HealAmount = 30
		
		local vm = owner:GetViewModel()
		if IsValid(vm) then
			local seq = vm:LookupSequence("suture")
			if seq > 0 then
				vm:SendViewModelMatchingSequence(seq)
			end
		end
		
		self:PlaySounds("suture")
	else
		-- QuikClot
		self:SetNextPrimaryFire(CT + 4.65)
		self:SetNextSecondaryFire(CT + 4.65)
		self.HealTime = CT + 4.2
		self.CurrentHeal = "quikclot"
		self.AmmoType = "Quikclots"
		self.HealAmount = 20
		
		local vm = owner:GetViewModel()
		if IsValid(vm) then
			local seq = vm:LookupSequence("quikclot")
			if seq > 0 then
				vm:SendViewModelMatchingSequence(seq)
			end
		end
		
		self:PlaySounds("quikclot")
	end
	
	self.Target = target
	self.OwnHeal = (target == owner)
	
	return true
end

if CLIENT then
	local White = Color(255, 255, 255, 255)
	local Black = Color(0, 0, 0, 255)
	local Green = Color(202, 255, 163, 255)
	local Grey = Color(200, 200, 200, 255)
	
	surface.CreateFont("IFAK_HUD24", {
		font = "Arial",
		size = 24,
		weight = 700,
		antialias = true
	})
	
	surface.CreateFont("IFAK_HUD36", {
		font = "Arial",
		size = 36,
		weight = 700,
		antialias = true
	})

	function SWEP:DrawHUD()
		local owner = self:GetOwner()
		if not IsValid(owner) then return end
		
		local x, y = ScrW() / 2, ScrH() / 2
		
		local target = self:FindHealTarget()
		local targetName = "СЕБЯ"
		if IsValid(target) and target != owner then
			targetName = target:Nick()
		end
		
		draw.SimpleTextOutlined(
			"ЦЕЛЬ ЛЕЧЕНИЯ: " .. targetName,
			"IFAK_HUD24",
			x, y + 200,
			White, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER,
			2, Black
		)
		
		-- Информация о расходниках
		local bandages = owner:GetAmmoCount("Bandages")
		local hemostats = owner:GetAmmoCount("Hemostats")
		local quikclots = owner:GetAmmoCount("Quikclots")
		
		-- Левая сторона - Бинты
		draw.SimpleTextOutlined(
			"БИНТЫ: " .. bandages,
			"IFAK_HUD36",
			x - 100, y + 125,
			White, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP,
			2, Black
		)
		
		if bandages > 0 then
			draw.SimpleTextOutlined(
				"ЛКМ - БИНТ",
				"IFAK_HUD24",
				x - 100, y + 100,
				Green, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP,
				2, Black
			)
			
			draw.SimpleTextOutlined(
				"+10 HP",
				"IFAK_HUD24",
				x - 100, y + 75,
				Green, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP,
				2, Black
			)
		end
		
		-- Правая сторона - Гемостаты/QuikClot
		if hemostats > 0 then
			draw.SimpleTextOutlined(
				"ГЕМОСТАТЫ: " .. hemostats,
				"IFAK_HUD36",
				x + 100, y + 125,
				White, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP,
				2, Black
			)
			
			draw.SimpleTextOutlined(
				"ПКМ - ГЕМОСТАТ",
				"IFAK_HUD24",
				x + 100, y + 100,
				Green, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP,
				2, Black
			)
			
			draw.SimpleTextOutlined(
				"+30 HP",
				"IFAK_HUD24",
				x + 100, y + 75,
				Green, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP,
				2, Black
			)
		else
			draw.SimpleTextOutlined(
				"QUIKCLOTS: " .. quikclots,
				"IFAK_HUD36",
				x + 100, y + 125,
				White, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP,
				2, Black
			)
			
			if quikclots > 0 then
				draw.SimpleTextOutlined(
					"ПКМ - QUIKCLOT",
					"IFAK_HUD24",
					x + 100, y + 100,
					Green, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP,
					2, Black
				)
				
				draw.SimpleTextOutlined(
					"+20 HP",
					"IFAK_HUD24",
					x + 100, y + 75,
					Green, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP,
					2, Black
				)
			end
		end
	end
end

