local assets =
{	
	Asset("ANIM", "anim/bloodsword.zip"),
	Asset("ANIM", "anim/swap_bloodsword.zip"),
	Asset ("ATLAS", "images/inventoryimages/bloodsword.xml")
}

local prefabs =
{
    "staffcastfx",
    "stafflight",
    "cutgrass",
}

local function onequip(inst, owner)
    owner.AnimState:OverrideSymbol("swap_object", "swap_bloodsword", "swap_nightmaresword")
    owner.AnimState:Show("ARM_carry") 
    owner.AnimState:Hide("ARM_normal") 
end

local function onunequip(inst, owner) 
    owner.AnimState:Hide("ARM_carry") 
    owner.AnimState:Show("ARM_normal") 
end

--Sacrifice Life
local function onattack(inst, owner, target)
	owner.components.health:DoDelta(5)
	
end

local DESTSOUNDS =
{
    {   --magic
        soundpath = "dontstarve/common/destroy_magic",
        ing = { "nightmarefuel", "livinglog" },
    },
    {   --cloth
        soundpath = "dontstarve/common/destroy_clothing",
        ing = { "silk", "beefalowool" },
    },
    {   --tool
        soundpath = "dontstarve/common/destroy_tool",
        ing = { "twigs" },
    },
    {   --gem
        soundpath = "dontstarve/common/gem_shatter",
        ing = { "redgem", "bluegem", "greengem", "purplegem", "yellowgem", "orangegem" },
    },
    {   --wood
        soundpath = "dontstarve/common/destroy_wood",
        ing = { "log", "boards" },
    },
    {   --stone
        soundpath = "dontstarve/common/destroy_stone",
        ing = { "rocks", "cutstone" },
    },
    {   --straw
        soundpath = "dontstarve/common/destroy_straw",
        ing = { "cutgrass", "cutreeds" },
    },
}
local DESTSOUNDSMAP = {}
for i, v in ipairs(DESTSOUNDS) do
    for i2, v2 in ipairs(v.ing) do
        DESTSOUNDSMAP[v2] = v.soundpath
    end
end
DESTSOUNDS = nil

local function CheckSpawnedLoot(loot)
    if not ((loot.components.inventoryitem ~= nil and loot.components.inventoryitem:IsHeld()) or loot:IsOnValidGround()) then
        SpawnPrefab("splash_ocean").Transform:SetPosition(loot.Transform:GetWorldPosition())
        if loot:HasTag("irreplaceable") then
            loot.Transform:SetPosition(FindSafeSpawnLocation(loot.Transform:GetWorldPosition()))
        else
            loot:Remove()
        end
    end
end

local function SpawnLootPrefab(inst, lootprefab)
    if lootprefab == nil then
        return
    end

    local loot = SpawnPrefab(lootprefab)
    if loot == nil then
        return
    end

    local x, y, z = inst.Transform:GetWorldPosition()

    if loot.Physics ~= nil then
        local angle = math.random() * 2 * PI
        loot.Physics:SetVel(2 * math.cos(angle), 10, 2 * math.sin(angle))

        if inst.Physics ~= nil then
            local len = loot.Physics:GetRadius() + inst.Physics:GetRadius()
            x = x + math.cos(angle) * len
            z = z + math.sin(angle) * len
        end

        loot:DoTaskInTime(1, CheckSpawnedLoot)
    end

    loot.Transform:SetPosition(x, y, z)

    return loot
end

local function destroystructure(staff, target)
    local recipe = AllRecipes[target.prefab]
    if recipe == nil then
        --Action filters should prevent us from reaching here normally
        return
    end

    local ingredient_percent =
        (   (target.components.finiteuses ~= nil and target.components.finiteuses:GetPercent()) or
            (target.components.fueled ~= nil and target.components.inventoryitem ~= nil and target.components.fueled:GetPercent()) or
            (target.components.armor ~= nil and target.components.inventoryitem ~= nil and target.components.armor:GetPercent()) or
            1
        ) / recipe.numtogive

    --V2C: Can't play sounds on the staff, or nobody
    --     but the user and the host will hear them!
    local caster = staff.components.inventoryitem.owner

    for i, v in ipairs(recipe.ingredients) do
        if caster ~= nil and DESTSOUNDSMAP[v.type] ~= nil then
            caster.SoundEmitter:PlaySound(DESTSOUNDSMAP[v.type])
        end
        if not string.find(v.type, "gem") then
            --V2C: always at least one in case ingredient_percent is 0%
            local amt = math.max(1, math.ceil(v.amount * ingredient_percent))
            for n = 1, amt do
                SpawnLootPrefab(target, v.type)
            end
        end
    end

    if caster ~= nil then
        caster.SoundEmitter:PlaySound("dontstarve/common/staff_dissassemble")

        if caster.components.sanity ~= nil then
            caster.components.sanity:DoDelta(-TUNING.SANITY_MEDLARGE)
        end
    end

    staff.components.finiteuses:Use(1)

    if target.components.inventory ~= nil then
        target.components.inventory:DropEverything()
    end

    if target.components.container ~= nil then
        target.components.container:DropEverything()
    end

    if target.components.stackable ~= nil then
        --if it's stackable we only want to destroy one of them.
        target.components.stackable:Get():Remove()
    else
        target:Remove()
    end
end

local function HasRecipe(guy)
    return guy.prefab ~= nil and AllRecipes[guy.prefab] ~= nil
end

local function onhaunt(inst)
    if math.random() <= TUNING.HAUNT_CHANCE_RARE then
        local target = FindEntity(inst, 20, HasRecipe, nil, { "INLIMBO" })
        if target ~= nil then
            destroystructure(inst, target) 
            SpawnPrefab("collapse_small").Transform:SetPosition(target.Transform:GetWorldPosition())
            inst.components.hauntable.hauntvalue = TUNING.HAUNT_LARGE
            return true
        end
    end
    return false
end


local function fn(Sim)


	local inst = CreateEntity()
	inst.entity:AddTransform()
	inst.entity:AddAnimState()
	inst.entity:AddNetwork()
		
	MakeInventoryPhysics(inst)
	
	if not TheWorld.ismastersim then
        return inst
  end
  
  inst.AnimState:SetBank("nightmaresword")
  inst.AnimState:SetBuild("bloodsword")
  inst.AnimState:PlayAnimation("idle")
    
  inst:AddTag("sharp")
  
	inst:AddComponent("weapon")
	inst.components.weapon:SetDamage(TUNING.SPEAR_DAMAGE *3)
	inst.components.weapon.onattack = onattack

  inst:AddComponent("finiteuses")
  inst.components.finiteuses:SetMaxUses(300)
  inst.components.finiteuses:SetUses(300)
  inst.components.finiteuses:SetOnFinished(inst.Remove)
    
	inst:AddComponent("inspectable")
	inst:AddComponent("inventoryitem")
	inst.components.inventoryitem.imagename = "bloodsword"
	inst.components.inventoryitem.atlasname = "images/inventoryimages/bloodsword.xml"
    
  inst:AddComponent("equippable")
  inst.components.equippable:SetOnEquip( onequip )
  inst.components.equippable:SetOnUnequip( onunequip)
  MakeHauntableLaunch(inst)

     inst.fxcolour = {220/255,20/255,60/255}
    inst:AddComponent("spellcaster")
    inst.components.spellcaster.canuseontargets = true
    inst.components.spellcaster.canonlyuseonrecipes = true
    inst.components.spellcaster:SetSpellFn(destroystructure)

    MakeHauntableLaunch(inst)
    AddHauntableCustomReaction(inst, onhaunt, true, false, true)
    
    return inst
end

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