require "prefabutil"

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

local prefabs =
{
    "collapse_small",
	"flint",
	"poop",
}

local function onhammered(inst, worker)
    if inst.components.burnable ~= nil and inst.components.burnable:IsBurning() then
        inst.components.burnable:Extinguish()
    end
    local x, y, z = inst.Transform:GetWorldPosition()
    SpawnPrefab("goldnugget").Transform:SetPosition(x, y, z)
	SpawnPrefab("boards").Transform:SetPosition(x, y, z)
    
    inst:Remove()
end

local function onhit(inst, worker)
	inst.AnimState:PushAnimation("idle", true)
end
local function onbuilt(inst)
    inst.components.pickable:MakeEmpty()
	inst.AnimState:PlayAnimation("pick",true)
end

local function OnRefuseItem(inst, giver, item)
    inst.SoundEmitter:PlaySound("dontstarve/pig/PigKingReject")
    inst.AnimState:PlayAnimation("hit")
end

local function onregenfn(inst)
    inst.AnimState:PlayAnimation("pickling", true)
end
local function makeemptyfn(inst)
    inst.AnimState:PlayAnimation("pick",true)
end
local function fn()
    local inst = CreateEntity()
	local kg = 0
	local pick = 0
    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddNetwork()
    MakeObstaclePhysics(inst, .2)
	inst.entity:AddDynamicShadow()
	inst.DynamicShadow:SetSize( 2,2 )
    inst.AnimState:SetBank("magicbox")
    inst.AnimState:SetBuild("magicbox")
	inst.AnimState:PlayAnimation("pickling",true)
    MakeSnowCoveredPristine(inst)
    inst:AddTag("structure")
    inst:AddTag("sign")
    inst.entity:SetPristine()
    if not TheWorld.ismastersim then
        return inst
    end

local function onpickedfn(inst)
	inst.AnimState:PlayAnimation("pick",true)
end
	inst:AddComponent("pickable")
	inst.components.pickable:SetUp("magicpower", TUNING.MARSHBUSH_REGROW_TIME*.25,2)
	inst.components.pickable.onregenfn = onregenfn
	inst.components.pickable.onpickedfn = onpickedfn
	inst.components.pickable.makeemptyfn = makeemptyfn
    inst:AddComponent("inspectable")
	inst:AddComponent("prototyper")
    inst:AddComponent("lootdropper")
	inst:ListenForEvent("onbuilt", onbuilt)

	MakeHauntableWork(inst)
    return inst
end
return Prefab("magicbox", fn, assets, prefabs),
    MakePlacer("magicbox_placer", "magicbox", "magicbox", "idle")
