local assets =
{
    Asset("ANIM", "anim/fireward.zip"),
	    Asset("ANIM", "anim/sentryward.zip"),
			    Asset("ATLAS", "inventoryimages/fireward.xml"),
    Asset("IMAGE", "inventoryimages/fireward.tex"),
}

local prefabs =
{
    "collapse_small",
    "globalmapicon",
}

local function RemoveCooldown(inst)
 inst.components.combat:GiveUp()
        inst.SoundEmitter:PlaySound("dontstarve/characters/wx78/spark")

         inst.AnimState:PlayAnimation("respawn")
        inst.AnimState:PushAnimation("idle_full_loop")

		inst:DoTaskInTime(1, function(inst)
		 inst:RemoveTag("cooldown")
		end)

end

local function SetTarget(inst, data)

if inst:HasTag("cooldown") then
inst:DoTaskInTime(1, function(inst)
 inst.components.combat:GiveUp()
		end)
else
 SpawnPrefab("sparks").Transform:SetPosition(inst.Transform:GetWorldPosition())
        inst.AnimState:PlayAnimation("attack")
        inst.AnimState:PushAnimation("despawn")
		        inst.AnimState:PushAnimation("idle_empty")

    inst.SoundEmitter:PlaySound("dontstarve/wilson/fireball_explo")



	 local victim = data.target
	  local attacker = inst
	     local x, y, z = attacker.Transform:GetWorldPosition()


 local projectile = SpawnPrefab("fire_charge")
         projectile:AddComponent("weapon")
        projectile.components.weapon:SetDamage(inst.components.combat.defaultdamage)
        projectile.components.weapon:SetRange(inst.components.combat.attackrange, inst.components.combat.attackrange+4)
projectile.Transform:SetPosition(x, y, z)
projectile.components.projectile:Throw(projectile, victim, attacker)
	 projectile.attacker = attacker

 if inst.components.combat and inst.components.combat.target ~= nil then

		 end
 inst:AddTag("cooldown")
   inst:DoTaskInTime(4, RemoveCooldown)
end
end

local function OnHealthDelta(inst, data)
if inst:HasTag("cooldown") then
        inst.AnimState:PlayAnimation("hit_empty")
        inst.AnimState:PushAnimation("idle_empty")
		else
	        inst.AnimState:PlayAnimation("hit_full")
        inst.AnimState:PushAnimation("idle_full_loop")
		end

end


local function Break(inst)

    local fx = SpawnPrefab("collapse_small")
    fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
    fx:SetMaterial("wood")
    inst:Remove()
end

local function onhammered(inst)
    inst.components.lootdropper:DropLoot()
    local fx = SpawnPrefab("collapse_small")
    fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
    fx:SetMaterial("wood")
    inst:Remove()
end

local function onhit(inst)
if inst:HasTag("cooldown") then
        inst.AnimState:PlayAnimation("hit_empty")
        inst.AnimState:PushAnimation("idle_empty")
		else
	        inst.AnimState:PlayAnimation("hit_full")
        inst.AnimState:PushAnimation("idle_full_loop")
		end

end

local function onbuilt(inst)
    inst.SoundEmitter:PlaySound("dontstarve/common/sentryward_craft")
    inst.AnimState:PlayAnimation("place")
    inst.AnimState:PushAnimation("idle_full_loop")
end

local function onburnt(inst)


    if inst.icon ~= nil then
        inst.icon:Remove()
        inst.icon = nil
    end
	inst:Remove()
end

local function onsave(inst, data)
    if inst:HasTag("burnt") or (inst.components.burnable ~= nil and inst.components.burnable:IsBurning()) then
        data.burnt = true
    end
end

local function onload(inst, data)
    if data ~= nil and data.burnt then
        inst.components.burnable.onburnt(inst)
    end
end

local function init(inst)
    if inst.icon == nil and not inst:HasTag("burnt") then
    end
end


local function retargetfn(inst)
    local playertargets = {}
    for i, v in ipairs(AllPlayers) do
        if v.components.combat.target ~= nil then
            playertargets[v.components.combat.target] = true
        end
    end

    return FindEntity(inst, 15,
        function(guy)
            return inst.components.combat:CanTarget(guy)
                and (playertargets[guy] or
                    (guy.components.combat.target ~= nil and guy.components.combat.target:HasTag("player")))

        end,
        { "_combat" }, --see entityreplica.lua
        { "INLIMBO", "player" }
    )
end

local function shouldKeepTarget(inst, target)
    return target ~= nil
        and target:IsValid()
        and target.components.health ~= nil
        and not target.components.health:IsDead()
        and inst:IsNear(target, 15)
end

local function ShareTargetFn(dude)
    return dude:HasTag("eyeturret")
end

local function OnAttacked(inst, data)
    local attacker = data ~= nil and data.attacker or nil
    if attacker ~= nil and not attacker:HasTag("player") then
        inst.components.combat:SetTarget(attacker)
        inst.components.combat:ShareTarget(attacker, 15, ShareTargetFn, 10)
    end
end

local function EquipWeapon(inst)
    if inst.components.inventory ~= nil and not inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS) then
        local weapon = CreateEntity()
        --[[Non-networked entity]]
        weapon.entity:AddTransform()
        weapon:AddComponent("weapon")
        weapon.components.weapon:SetDamage(inst.components.combat.defaultdamage)
        weapon.components.weapon:SetRange(inst.components.combat.attackrange, inst.components.combat.attackrange+4)
        weapon.components.weapon:SetProjectile("fire_charge")
        weapon:AddComponent("inventoryitem")
        weapon.persists = false
        weapon.components.inventoryitem:SetOnDroppedFn(inst.Remove)
        weapon:AddComponent("equippable")

        inst.components.inventory:Equip(weapon)
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddNetwork()




    MakeObstaclePhysics(inst, 0.8)

    inst.AnimState:SetBank("fireward")
    inst.AnimState:SetBuild("fireward")
    inst.AnimState:PlayAnimation("idle_full_loop", true)
    inst.AnimState:SetBloomEffectHandle("shaders/anim.ksh")
	    inst.Transform:SetScale(1.5, 1.5, 1.5)

    inst:AddTag("structure")



    inst:AddTag("largecreature")
    inst:AddTag("eyeturret")
    inst:AddTag("companion")

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst.AnimState:SetTime(math.random() * 1.8)

    -----------------------
    MakeSmallBurnable(inst, nil, nil, true)
    inst:ListenForEvent("burntup", onburnt)

    MakeSmallPropagator(inst)
    MakeHauntableWork(inst)

    -------------------------
    inst:AddComponent("lootdropper")
    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(4)
    inst.components.workable:SetOnFinishCallback(onhammered)
    inst.components.workable:SetOnWorkCallback(onhit)

    -----------------------------
    inst:AddComponent("inventory")


	---------------------------------------------------
	 inst:AddComponent("health")
    inst.components.health:SetMaxHealth(600)

    inst:ListenForEvent("healthdelta", OnHealthDelta)
-------------------------------------------------------
    inst:AddComponent("combat")
    inst.components.combat:SetRange(6,10)
    inst.components.combat:SetDefaultDamage(20)
    inst.components.combat:SetAttackPeriod(10)
    inst.components.combat:SetRetargetFunction(1, retargetfn)
    inst.components.combat:SetKeepTargetFunction(shouldKeepTarget)
	    inst:ListenForEvent("newcombattarget", SetTarget)
		   inst:ListenForEvent("attacked", OnAttacked)
	--------------------------------------------------------

	    EquipWeapon(inst)

    inst:AddComponent("inspectable")

    inst:ListenForEvent("death", Break)

    inst:ListenForEvent("onbuilt", onbuilt)
    inst.OnSave = onsave
    inst.OnLoad = onload

    inst:DoTaskInTime(0, init)

    return inst
end

return Prefab("fireward", fn, assets, prefabs),
    MakePlacer("fireward_placer", "fireward", "fireward", "idle_full")
