require "prefabutil"

local assets =
{
    Asset("ANIM", "anim/millbuilder.zip"),
	Asset("ATLAS", "images/inventoryimages/millbuilder.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
    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, 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 OnGetItemFromPlayer(inst, giver, item)
local x, y, z = inst.Transform:GetWorldPosition()
y = 1
x = x+2
--金块=大块金属+碳
    if item.prefab == "goldnugget" 
	then 
	inst.AnimState:PlayAnimation("idle")
    SpawnPrefab("coherer").Transform:SetPosition(x, y, z)
	SpawnPrefab("c").Transform:SetPosition(x, y, z)
    end
--燧石=金属碎片
	if item.prefab == "flint" 
	then 
	inst.AnimState:PlayAnimation("idle")
    SpawnPrefab("coherer_small").Transform:SetPosition(x, y, z)
    end
--大块金属=铁+铜+铅
	if item.prefab == "coherer" 
	then 
	inst.AnimState:PlayAnimation("idle")
    SpawnPrefab("cu").Transform:SetPosition(x, y, z)
	SpawnPrefab("fe").Transform:SetPosition(x, y, z)
    end
	
end

local function OnRefuseItem(inst, giver, item)
    inst.SoundEmitter:PlaySound("dontstarve/pig/PigKingReject")
    inst.AnimState:PlayAnimation("hit")
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( 3, 4 )
    inst.AnimState:SetBank("millbuilder")
    inst.AnimState:SetBuild("millbuilder")
    inst.AnimState:PlayAnimation("idle")
    MakeSnowCoveredPristine(inst)
    inst:AddTag("structure")
    inst:AddTag("sign")
    inst.entity:SetPristine()
    if not TheWorld.ismastersim then
        return inst
    end
	--分解
     inst:AddComponent("trader")
	 inst.components.trader.onaccept = OnGetItemFromPlayer
	
	inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(75)
    inst.components.workable:SetOnFinishCallback(onhammered)
    inst.components.workable:SetOnWorkCallback(onhit)
    inst:AddComponent("inspectable")
    inst:AddComponent("lootdropper")
	   inst:ListenForEvent("onbuilt", onbuilt)
	   MakeHauntableWork(inst)
    return inst
end
return Prefab("millbuilder", fn, assets, prefabs),
    MakePlacer("millbuilder_placer", "millbuilder", "millbuilder", "idle")
