--[[
BY
 _____   _____   __   _  
|  _  \ /  _  \ |  \ | | 
| | | | | | | | |   \| | 
| | | | | | | | | |\   | 
| |_| | | |_| | | | \  | 
|_____/ \_____/ |_|  \_| 

]]

require "prefabutil"

local containers = require("containers")


local assets =
{
    Asset("ANIM", "anim/donforge.zip"),
	Asset("ANIM", "anim/ui_forge_don.zip"),
	
	Asset("IMAGE", "images/minimap/donforgeworkbenchmap.tex"),
	Asset("ATLAS", "images/minimap/donforgeworkbenchmap.xml"),	
}

local prefabs =
{
}

local isvaliditemtoforge = {
	"axe", 
	"pickaxe", 
	"spear", 
	"green_cap",
	"red_cap",
	"nightmarefuel",
}


local forgerecipes = {
	{ prefabname = "donrpgtools_axe_blue", ingA = "axe", ingB = "green_cap", forgetime = 18, },
	{ prefabname = "donrpgtools_axe_red", ingA = "axe", ingB = "red_cap", forgetime = 22, },
	{ prefabname = "donrpgtools_axe_purple", ingA = "axe", ingB = "nightmarefuel", forgetime = 28, },
	
	{ prefabname = "donrpgtools_pickaxe_blue", ingA = "pickaxe", ingB = "green_cap", forgetime = 19, },
	{ prefabname = "donrpgtools_pickaxe_red", ingA = "pickaxe", ingB = "red_cap", forgetime = 23, },
	{ prefabname = "donrpgtools_pickaxe_purple", ingA = "pickaxe", ingB = "nightmarefuel", forgetime = 30, },
	
	{ prefabname = "donrpgtools_spear_blue", ingA = "spear", ingB = "green_cap", forgetime = 19, },
	{ prefabname = "donrpgtools_spear_red", ingA = "spear", ingB = "red_cap", forgetime = 24, },
	{ prefabname = "donrpgtools_spear_purple", ingA = "spear", ingB = "nightmarefuel", forgetime = 33, },
}



local function onhammered(inst, worker)

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

	inst.Light:Enable(false)
	inst.inuse = false
	inst.forgeitemtime = 0
	
    inst.components.lootdropper:DropLoot()
    local fx = SpawnPrefab("collapse_small")
    fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
    fx:SetMaterial("metal")
    inst:Remove()
end

local function onhit(inst, worker)		
	SpawnPrefab("sparks").Transform:SetPosition(inst.Transform:GetWorldPosition())
	SpawnPrefab("donfx_dark_smoke").Transform:SetPosition(inst.Transform:GetWorldPosition())
end

local function onbuilt(inst)
    inst.AnimState:PlayAnimation("place")
    inst.AnimState:PushAnimation("idle")
    inst.SoundEmitter:PlaySound("rpgdongeralsounds/rpgdongeralsounds/forge_place")
end


local function sparksfx(inst)
    if inst.inuse == true then
        SpawnPrefab("sparks").Transform:SetPosition(inst.Transform:GetWorldPosition())
		inst:DoTaskInTime(1.2 + math.random() * 2, sparksfx)
    end  
end

local function onopen(inst)
	if inst.inuse == false then
		
	end
	
	if inst.inuse == true then
		inst.components.container:Close()
	end
end

local function onclose(inst)
    if inst.inuse == false then
		inst.AnimState:PlayAnimation("idle")
		inst.SoundEmitter:KillSound("loopsoundmakeforge")
		inst.Light:Enable(false)
    end
end

local function onfar(inst)
    inst.components.container:Close()
end



local function Forge_isdone(inst)	
	SpawnPrefab("donfx_dark_smoke").Transform:SetPosition(inst.Transform:GetWorldPosition())	

	inst.components.container:DestroyContents()
	
	local potionitem = SpawnPrefab(inst.makeforgeitemprefab)
	
    local pt = Vector3(inst.Transform:GetWorldPosition()) + Vector3(0,1,0)
    potionitem.Transform:SetPosition(pt:Get())
    local down = TheCamera:GetDownVec()
    local angle = math.atan2(down.z, down.x) + (math.random()*60)*DEGREES
    local sp = 3 + math.random()
    potionitem.Physics:SetVel(sp*math.cos(angle), math.random()*2+8, sp*math.sin(angle))
		
	inst.AnimState:PlayAnimation("idle", true)
	inst.SoundEmitter:KillSound("loopsoundmakeforge")
    inst.SoundEmitter:PlaySound("rpgdongeralsounds/rpgdongeralsounds/forge_isdone")
	inst.Light:Enable(false)
	inst.inuse = false
	inst.forgeitemtime = 0	
	inst.makeforgeitemprefab = ""
	inst.components.container.canbeopened = true
end


local function Forge_makeitem(inst, timetocook, recipeprefab)	
	inst.forgeitemtime = timetocook
	inst.makeforgeitemprefab = recipeprefab
	
	inst.AnimState:PlayAnimation("inuseforge", true)

	inst.SoundEmitter:KillSound("loopsoundmakeforge")
    inst.SoundEmitter:PlaySound("rpgdongeralsounds/rpgdongeralsounds/forge_loopmake", "loopsoundmakeforge")
	inst.Light:Enable(true)
	inst.inuse = true
	inst.components.container:Close()	
	inst.components.container.canbeopened = false

	inst:DoTaskInTime(inst.forgeitemtime, Forge_isdone)
	sparksfx(inst)	
end

local function FindItemDon(inst, prefabname)
	return inst.components.container:Has(prefabname, 1)
end

local function Forge_CheckRecipes(inst)
local selectedrecipeforge = ""
local selectedforgeitemtime = 0
local isok = false

	for k,v in ipairs(forgerecipes) do
		if v.prefabname ~= nil and isok == false then
			if FindItemDon(inst, v.ingA) and FindItemDon(inst, v.ingB) then
				selectedrecipeforge = v.prefabname
				selectedforgeitemtime = v.forgetime
				isok = true
			end
		end
	end


	if isok == true and selectedrecipeforge ~= nil and selectedforgeitemtime > 0 and inst.components.container.opener ~= nil then
		if inst.components.container.opener ~= nil and inst.components.container.opener.components.sanity ~= nil then
			inst.components.container.opener.components.sanity:DoDelta(-5)
		end
		
		Forge_makeitem(inst, selectedforgeitemtime, selectedrecipeforge)					
	else
		inst.SoundEmitter:PlaySound("rpgdongeralsounds/rpgdongeralsounds/forge_deny")
		inst.components.container:DropEverything()
	end
	
	inst.components.container:Close()

end


local function onsave(inst, data)
	data.inuse = inst.inuse
	data.forgeitemtime = inst.forgeitemtime
	data.makeforgeitemprefab = inst.makeforgeitemprefab
end

local function onload(inst, data)
	inst.Light:Enable(false)
	
	if data ~= nil and inst.inuse ~= nil and data.forgeitemtime ~= nil and data.makeforgeitemprefab ~= nil then
		inst.inuse = data.inuse
		inst.forgeitemtime = data.forgeitemtime
		inst.makeforgeitemprefab = data.makeforgeitemprefab
	end
	
	if inst.inuse == true and inst.forgeitemtime ~= nil and inst.makeforgeitemprefab ~= nil then
		if inst.forgeitemtime > 0 then
				Forge_makeitem(inst, inst.forgeitemtime, inst.makeforgeitemprefab)
			else
				inst.inuse = false
				inst.forgeitemtime = 0
				inst.makeforgeitemprefab = ""
				inst.components.container:DropEverything()
				inst.components.container:Close()
		end
	end
end


local function oncookmagic(inst)
	if inst.components.container ~= nil then
		Forge_CheckRecipes(inst)
	else
		print("erro grave!")	
	end			
end


local ui_forge_make =
{
    widget =
    {
        slotpos =
        {
            Vector3(-45, -17, 0), 
            Vector3(45, -17, 0),
        },
        animbank = "ui_forge_don",
        animbuild = "ui_forge_don",
        pos = Vector3(0, 140, 0),
        side_align_tip = 160,

		buttoninfo  =
		{
			text = STRINGS.DONBTN_FORGE,
			position = Vector3(0, -78, 0),
			
			fn = function(inst)--clicou no botão
				if inst.components.container ~= nil then
					BufferedAction(inst.components.container.opener, inst, ACTIONS.CONTAINERDON):Do()
				elseif inst.replica.container ~= nil and not inst.replica.container:IsBusy() then
					SendRPCToServer(RPC.DoWidgetButtonAction, ACTIONS.CONTAINERDON.code, inst, ACTIONS.CONTAINERDON.mod_name)
				end
			end,

			validfn = function(inst)--checar se pode continuar 
				  return inst.replica.container ~= nil and inst.replica.container:IsFull()
			end,
			
		}
    },
	
	type = "cooker",
	acceptsstacks = false,
	issidewidget = false,  

	itemtestfn = function(container, item, slot)
	
		for i, v in ipairs(isvaliditemtoforge) do
			if (v == item.prefab) then
				return true
			end	
		end	

		return false
		
	end,
}

local oldwidgetsetup = containers.widgetsetup
function containers.widgetsetup(container, prefab, data, ...)
	if container.inst.prefab == "donforge_workbench" or prefab == "donforge_workbench" then
        for k, v in pairs(ui_forge_make) do
            container[k] = v
        end
        container:SetNumSlots(container.widget.slotpos ~= nil and #container.widget.slotpos or 0)
        return
	end
	
    return oldwidgetsetup(container, prefab, data, ...)
end


local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddMiniMapEntity()
    inst.entity:AddLight()
    inst.entity:AddNetwork()

    MakeObstaclePhysics(inst, 2, 1.2)

    inst.MiniMapEntity:SetIcon("donforgeworkbenchmap.tex")

    inst.Light:Enable(false)
    inst.Light:SetRadius(.6)
    inst.Light:SetFalloff(1)
    inst.Light:SetIntensity(.3)
    inst.Light:SetColour(247/255, 26/255, 26/255)

    inst:AddTag("structure")

    inst.AnimState:SetBank("donforge")
    inst.AnimState:SetBuild("donforge")
    inst.AnimState:PlayAnimation("idle")
	
    MakeSnowCoveredPristine(inst)

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then	
		inst.OnEntityReplicated = function(inst) inst.replica.container:WidgetSetup("donforge_workbench", ui_forge_make) end	
		return inst
	end
		
	inst.inuse = false
	inst.forgeitemtime = 0
	inst.makeforgeitemprefab = ""

    inst:AddComponent("lootdropper")
    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(4)
    inst.components.workable:SetOnFinishCallback(onhammered)
    inst.components.workable:SetOnWorkCallback(onhit)
	
	
	inst:AddComponent("playerprox")
    inst.components.playerprox:SetDist(3,5)
    inst.components.playerprox:SetOnPlayerFar(onfar)

	inst:AddComponent("container_don")
	inst.components.container_don.onmagiccookfn = oncookmagic
	
	inst:AddComponent("container")
	inst.components.container:WidgetSetup("donforge_workbench", ui_forge_make)
	inst.components.container.onopenfn = onopen
	inst.components.container.onclosefn = onclose
	inst:ListenForEvent("itemget", function(inst, data)
		if inst.components.container ~= nil then
			inst.components.container:Open(ThePlayer)
		end
	end)
	inst.components.container.canbeopened = true
	


    MakeSnowCovered(inst)
    inst:ListenForEvent("onbuilt", onbuilt)

    inst.OnSave = onsave 
    inst.OnLoad = onload

    return inst
end


return Prefab("donforge_workbench", fn, assets, prefabs),
    MakePlacer("donforge_workbench_placer", "donforge", "donforge", "idle")
