require "prefabutil"

local assets =
{
    Asset("ANIM", "anim/asttable.zip"),
	Asset("ATLAS", "images/inventoryimages/asttable.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:PlayAnimation("hit")
	inst.AnimState:PushAnimation("idle", true)
end


local function onbuilt(inst)
    inst.SoundEmitter:PlaySound("dontstarve/common/sign_craft")
end
local function OnRefuseItem(inst, giver, item)
    inst.SoundEmitter:PlaySound("dontstarve/pig/PigKingReject")
    inst.AnimState:PlayAnimation("hit")
end
local function complete_doonact(inst)
    if inst._activecount > 1 then
        inst._activecount = inst._activecount - 1
    else
        inst._activecount = 0
        --inst.SoundEmitter:KillSound("sound")
    end

    --inst.SoundEmitter:PlaySound("dontstarve/common/researchmachine_lvl3_ding")
end
local function onactivate(inst)
    inst._activecount = inst._activecount + 1
    --if not inst.SoundEmitter:PlayingSound("sound") then
    --    inst.SoundEmitter:PlaySound("dontstarve/common/ancienttable_craft", "sound")
    --end

    inst:DoTaskInTime(1.5, complete_doonact)
end

local function fn()
    local inst = CreateEntity()
    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("millbox")
    inst.AnimState:SetBuild("millbox")
    inst.AnimState:PlayAnimation("idle")
    MakeSnowCoveredPristine(inst)
    inst:AddTag("structure")
    inst:AddTag("sign")
    inst.entity:SetPristine()
    if not TheWorld.ismastersim then
        return inst
    end
	inst._activecount = 0
	inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(5)
    inst.components.workable:SetOnFinishCallback(onhammered)
    inst.components.workable:SetOnWorkCallback(onhit)
    inst:AddComponent("inspectable")
	inst:AddComponent("prototyper")
    inst.components.prototyper.onactivate = onactivate
	inst.components.prototyper.trees = TUNING.PROTOTYPER_TREES.TOU_ASTITEM_TWO
    inst:AddComponent("lootdropper")
	   inst:ListenForEvent("onbuilt", onbuilt)
	   MakeHauntableWork(inst)
    return inst
end
return Prefab("asttable", fn, assets, prefabs),
    MakePlacer("asttable_placer", "asttable", "asttable", "idle")
