local assets =
{
	Asset("ANIM", "anim/armor_tungsten.zip"),
}

local function OnBlocked(owner)
    owner.SoundEmitter:PlaySound("dontstarve/wilson/hit_armour")
end

local function armorrepair(inst, owner)
	local owner = inst.components.inventoryitem.owner
	if inst.components.inventoryitem == nil or owner.components.inventory == nil then
        return
  end
	if owner and owner.components.health ~= 0 and inst.components.armor:GetPercent() < 1 and inst.repair_time == 1 then
		owner.components.health.currenthealth = owner.components.health.currenthealth-10
		owner.components.health:ForceUpdateHUD()
		inst.components.armor:SetPercent(inst.components.armor:GetPercent()+0.02)
	end
end

local function freezefn(attacked,data)
	if data and data.attacker and data.attacker.components.freezable then
        data.attacker.components.freezable:AddColdness(1.5)
        data.attacker.components.freezable:SpawnShatterFX()
    end
end

local function onequip(inst, owner)
    owner.AnimState:OverrideSymbol("swap_body", "armor_tungsten", "swap_body")
		inst.repair_time = 1
		if inst.repair_time == 1 then
			inst.task = inst:DoPeriodicTask(10, function() armorrepair(inst, 2) end)
		end
    inst:ListenForEvent("attacked", freezefn, owner)

    inst:ListenForEvent("blocked", OnBlocked, owner)
end

local function onunequip(inst, owner)
    owner.AnimState:ClearOverrideSymbol("swap_body")
		inst.repair_time = 0
		if inst.task ~= nil then
	        inst.task:Cancel()
	        inst.task = nil
	   end
    inst:RemoveEventCallback("blocked", OnBlocked, owner)
		inst:RemoveEventCallback("attacked", freezefn, owner)
end

local function fn()
	local inst = CreateEntity()

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

    MakeInventoryPhysics(inst)

    inst.AnimState:SetBank("armor_ruins")
    inst.AnimState:SetBuild("armor_tungsten")
    inst.AnimState:PlayAnimation("anim")

	inst:AddComponent("heater")
    inst.components.heater.iscooler = true
	inst.components.heater.carriedheat=TUNING.BLUEGEM_COOLER
    inst.components.heater.equippedheat = TUNING.BLUEGEM_COOLER*3
    inst:AddTag("metal")

    inst.foleysound = "dontstarve/movement/foley/metalarmour"

    if not TheWorld.ismastersim then
        return inst
    end

    inst.entity:SetPristine()

    inst:AddComponent("inspectable")

    inst:AddComponent("inventoryitem")
	inst.components.inventoryitem.atlasname = "tungstenimages/inventoryimages.xml"

    inst:AddComponent("armor")
    inst.components.armor:InitCondition(9999,TUNING.ARMORTUNGSTEN_ABSORPTION)

    inst:AddComponent("equippable")
    inst.components.equippable.equipslot = EQUIPSLOTS.BODY
		inst.components.equippable.walkspeedmult = 0.9
    inst.components.equippable:SetOnEquip(onequip)
    inst.components.equippable:SetOnUnequip(onunequip)
    MakeHauntableLaunch(inst)
    return inst
end

return Prefab("common/inventory/armor_tungsten", fn, assets)
