include("shared.lua")

function ENT:Initialize()
	self.TargetSkin = 1
	self.IsSpinning = false
	self.ReelAngle = Angle(0, 0, 0)
	self.TargetAngle = Angle(0, 0, 0)
	self:SetColor(Color(180, 180, 180))
end

local function LerpAngleCustom(value, start, _end)
    local min = 0
    local max = 360
    local half = math.abs((max - min) / 2)
    local retval = 0
    local diff = 0
    if ((_end - start) < -half) then
        diff = ((max - start) + _end) * value
        retval = start + diff
    elseif ((_end - start) > half) then
        diff = -((max - _end) + start) * value
        retval = start + diff
    else 
    	retval = start + (_end - start) * value
    end
    return retval
end

function ENT:Think()
	local tb = self:GetTable()
	if tb.IsSpinning then
		tb.ReelAngle:RotateAroundAxis(Vector(0, 1, 0), 850 * FrameTime())
		self:SetLocalAngles(tb.ReelAngle)
		tb.IsSpinning = true
	elseif tb.ReelAngle.p != tb.TargetAngle.p then
		tb.ReelAngle.p = LerpAngleCustom(10 * FrameTime(), tb.ReelAngle.p, tb.TargetAngle.p)
		self:SetLocalAngles(tb.ReelAngle)
	else
		self:SetLocalAngles(tb.ReelAngle)
	end
	if self:GetSkin() != tb.TargetSkin then
		self:SetSkin(tb.TargetSkin)
	end
end

function ENT:Spin()
	self.IsSpinning = true
	self:SetSkin(2)
	self.TargetSkin = 2
end

function ENT:Flash()
	self:SetSkin(3)
	self.TargetSkin = 3
	timer.Simple(0.12, function()
		if !IsValid(self) then return end
		self:SetSkin(1)
		self.TargetSkin = 1
		timer.Simple(0.12, function()
			if !IsValid(self) then return end
			self:SetSkin(3)
			self.TargetSkin = 3
			timer.Simple(0.12, function()
				if !IsValid(self) then return end
				self:SetSkin(1)
				self.TargetSkin = 1
			end)
		end)
	end)
end

function ENT:StopReel(index)
	local target_amt = -(45 * (index - 1))
	self.TargetAngle = Angle(target_amt, 0, 0)
	self.ReelAngle = Angle(target_amt + 30, 0, 0)
	self:SetLocalAngles(self.ReelAngle)
	self.IsSpinning = false
	self:SetSkin(1)
	self.TargetSkin = 1
end