local function OnAttached(inst, target)
    inst.entity:SetParent(target.entity)
    inst.Transform:SetPosition(0, 0, 0) --in case of loading
    
	if not target:HasTag("doing") and not inst.no_anim then
		target.sg:GoToState("powerup")
		target.SoundEmitter:PlaySound((target.talker_path_override or "dontstarve/characters/")..(target.soundsname or target.prefab).."/pose")
	
		for _,v in pairs({ "attune_in", "chester_transform" }) do
			SpawnPrefab(v.."_fx").Transform:SetFromProxy(target.GUID)
		end
	end
	
	local combat = target.components.combat
	if combat ~= nil then
		target:AddTag("inebriate")
		
		inst._CalcDamage = combat.CalcDamage
		combat.CalcDamage = function(self, target, weapon, ...)
			local basemultiplier = self.damagemultiplier or 1
			
			self.damagemultiplier = basemultiplier + TUNING.HORN_BUFF_POWER
			local damage = inst._CalcDamage(self, target, weapon, ...)
			self.damagemultiplier = basemultiplier

			return damage
		end
	else
		inst.components.debuff:Stop()
	end
	
    inst:ListenForEvent("death", function()
        inst.components.debuff:Stop()
    end, target)
end

local function OnDetached(inst, target)	
	target.sg:GoToState("powerdown")
	target.SoundEmitter:PlaySound((target.talker_path_override or "dontstarve/characters/")..(target.soundsname or target.prefab).."/eye_rub_vo")
	target.SoundEmitter:PlaySound("dontstarve/pig/PigKingThrowGold")
	
	for _,v in pairs({ "attune_out", "chester_transform" }) do
		SpawnPrefab(v.."_fx").Transform:SetFromProxy(target.GUID)
	end
	
	local combat = target.components.combat
	if combat ~= nil then
		target:RemoveTag("inebriate")
		combat.CalcDamage = inst._CalcDamage
	end
	
	inst:Remove()
end

local function OnTimerDone(inst, data)
    if data.name == "hornbuffover" then
        inst.components.debuff:Stop()
    end
end

local function OnExtended(inst, target)
    inst.components.timer:StopTimer("hornbuffover")
    inst.components.timer:StartTimer("hornbuffover", inst.bufftime)
end

local function fn()
    local inst = CreateEntity()

    if not TheWorld.ismastersim then
        --Not meant for client!
        inst:DoTaskInTime(0, inst.Remove)

        return inst
    end

    inst.entity:AddTransform()

    --[[Non-networked entity]]
    --inst.entity:SetCanSleep(false)
    inst.entity:Hide()
    inst.persists = false

    inst:AddTag("CLASSIFIED")

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff:SetDetachedFn(OnDetached)
    inst.components.debuff:SetExtendedFn(OnExtended)
    inst.components.debuff.keepondespawn = true

    inst.bufftime = TUNING.HORN_BUFF_TIME + math.random(-5, 5)
	
	inst:AddComponent("timer")
    inst.components.timer:StartTimer("hornbuffover", inst.bufftime)
    inst:ListenForEvent("timerdone", OnTimerDone)
	
	inst.OnLoad = function() inst.no_anim = true end

    return inst
end

return Prefab("hornbuff", fn)