require "prefabutil"

local assets=
{
	Asset("ANIM", "anim/firebox.zip"),
	Asset("ANIM", "anim/ui_chest_3x3.zip"),
	Asset("IMAGE", "images/inventoryimages/firebox.tex"),
	Asset("ATLAS", "images/inventoryimages/firebox.xml"),	
}

local function firefive(inst, owner)
     if owner:HasTag("fire1") and owner:HasTag("fire2") and owner:HasTag("fire3") and owner:HasTag("fire4") and owner:HasTag("fire5") and  inst:HasTag("firebox") then
	local hungerpercent = owner.components.hunger:GetPercent()
	local healthpercent = owner.components.health:GetPercent()
	local sanitypercent = owner.components.sanity:GetPercent()
        if healthpercent < hungerpercent and healthpercent < sanitypercent then
        owner.components.health:DoDelta(20)
            if hungerpercent < sanitypercent then
            owner.components.hunger:DoDelta(10)
            else
            owner.components.sanity:DoDelta(10)
            end
        elseif hungerpercent < healthpercent and hungerpercent < sanitypercent then
        owner.components.hunger:DoDelta(20)
            if healthpercent < sanitypercent then
            owner.components.health:DoDelta(10)
            else
            owner.components.sanity:DoDelta(10)
            end
        else
        owner.components.sanity:DoDelta(20)
            if healthpercent < hungerpercent then
            owner.components.health:DoDelta(10)
            else
            owner.components.hunger:DoDelta(10)
            end
        end

        inst.components.heater.equippedheat = 40 
        inst.components.fueled:DoDelta(-30)
            inst.components.fueled.rate = 0.5
    else
        inst.components.heater.equippedheat = 20 
            inst.components.fueled.rate = 1
    end

end
local function onequip(inst, owner) 
        owner:AddTag("fire5")
        inst.Light:Enable(true)
        inst.components.container.widgetpos = Vector3(410,-180,0)
        inst.components.container:Open(owner)

    inst.task = inst:DoPeriodicTask(60, function() firefive(inst, owner) end)
end

local function onunequip(inst, owner) 
        owner:RemoveTag("fire5")
    inst.components.container:Close(owner)
inst.task:Cancel() inst.task = nil
        inst.components.heater.equippedheat = 20 
            inst.components.fueled.rate = 1
end

local function fuelupdate(inst)
        if GetSeasonManager() and GetSeasonManager():IsRaining() then
            inst.components.fueled.rate = 1 + TUNING.FIREPIT_RAIN_RATE*GetSeasonManager():GetPrecipitationRate()
        else
            inst.components.fueled.rate = 1
        end
    local fuelpercent = inst.components.fueled:GetPercent()
    inst.Light:SetIntensity(Lerp(0.4, 0.6, fuelpercent))
    inst.Light:SetRadius(Lerp(3, 5, fuelpercent))
    inst.Light:SetFalloff(.9)
     if fuelpercent >0.05 then
         inst:AddTag("firebox")
     else
       inst:RemoveTag("firebox")
     end
end

local function oncarry(inst)
    inst.components.machine.ison = true
    inst:AddComponent("inventoryitem")
    inst.components.inventoryitem.atlasname = "images/inventoryimages/firebox.xml"
    inst.components.inventoryitem.cangoincontainer = false
        inst.Light:Enable(true)
	inst:AddComponent("equippable")
	if EQUIPSLOTS["NECK"] then
		inst.components.equippable.equipslot = EQUIPSLOTS.NECK
	else
		inst.components.equippable.equipslot = EQUIPSLOTS.HEAD
	end
	inst.components.equippable:SetOnEquip( onequip )
        inst.components.equippable:SetOnUnequip( onunequip )
    end

local function onset(inst)
    inst.components.machine.ison = false
       inst:RemoveComponent("inventoryitem")
       inst:RemoveComponent("equippable")
        inst.Light:Enable(true)
    inst.components.container.widgetpos = Vector3(0,200,0)
end

local function onopen(inst) 
	inst.AnimState:PlayAnimation("open") 
	inst.SoundEmitter:PlaySound("dontstarve/wilson/chest_open")		
end 

local function onclose(inst) 
	inst.AnimState:PlayAnimation("close") 
	inst.SoundEmitter:PlaySound("dontstarve/wilson/chest_close")		
end 

local function onhammered(inst, worker)
	inst.components.lootdropper:DropLoot()
	inst.components.container:DropEverything()
	SpawnPrefab("collapse_small").Transform:SetPosition(inst.Transform:GetWorldPosition())
	inst.SoundEmitter:PlaySound("dontstarve/common/destroy_metal")
	
	inst:Remove()
end

local function onhit(inst, worker)
	inst.AnimState:PlayAnimation("hit")
	inst.components.container:DropEverything()
	inst.AnimState:PushAnimation("closed", false)
	inst.components.container:Close()
end

local function onbuilt(inst)
	inst.AnimState:PlayAnimation("place")
	inst.AnimState:PushAnimation("closed", false)
end

local slotpos = {}

for y = 2, 0, -1 do
	for x = 0, 2 do
		table.insert(slotpos, Vector3(80*x-80*2+80, 80*y-80*2+80,0))
	end
end

local function itemtest(inst, item, slot)
	return item.components.edible and item.components.perishable 
end

		
local function fn(Sim)
	local inst = CreateEntity()
	
    inst:AddTag("structure")
	
	inst.entity:AddTransform()
	inst.entity:AddAnimState()
	inst.entity:AddSoundEmitter()
    
	local minimap = inst.entity:AddMiniMapEntity()
	minimap:SetIcon( "icebox.png" )
	

	inst.AnimState:SetBank("pandoras_chest_large")
        inst.AnimState:SetBuild("firebox")
    inst.AnimState:PlayAnimation("closed")
    
    inst:AddComponent("inspectable")

    inst:AddComponent("container")

    inst.components.container.itemtestfn = itemtest
    inst.components.container:SetNumSlots(#slotpos)   
    inst.components.container.widgetslotpos = slotpos
    inst.components.container.widgetanimbank = "ui_chest_3x3"
    inst.components.container.widgetanimbuild = "ui_chest_3x3"
    inst.components.container.widgetpos = Vector3(0,200,0)
	inst.components.container.widgetbgimagetint = {r=.98,g=.05,b=.10,a=1}

    inst.components.container.onopenfn = onopen
    inst.components.container.onclosefn = onclose
  
    inst:AddComponent("machine")
    inst.components.machine.turnonfn = oncarry
    inst.components.machine.turnofffn = onset
  
    inst:AddComponent("lootdropper")
    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(2)
	inst.components.workable:SetOnFinishCallback(onhammered)
	inst.components.workable:SetOnWorkCallback(onhit) 

        local light = inst.entity:AddLight()
        light:SetColour(238/255, 17/255, 39/255)
        inst.Light:Enable(true)


    inst:AddComponent("fueled")
        inst.components.fueled.fueltype = "GEMFUEL"
    inst.components.fueled.maxfuel = 480 * 5
    inst.components.fueled:SetUpdateFn(fuelupdate)
    inst.components.fueled.accepting = true        
    inst.components.fueled:InitializeFuelLevel(480)
    inst.components.fueled.ontakefuelfn = function() inst.SoundEmitter:PlaySound("dontstarve/common/fireAddFuel") end
    inst.components.fueled:StartConsuming()  

           inst:AddComponent("heater")
        inst.components.heater.iscooler = true
        inst.components.heater.equippedheat = 20 
	
    inst:ListenForEvent( "onbuilt", onbuilt)
	MakeSnowCovered(inst, .01)	
    return inst
end

return Prefab( "common/firebox", fn, assets),
		MakePlacer("common/icebox_placer", "icebox", "ice_box", "closed") 

