PrefabFiles = {
	"miningmachine",
	"wrench",
	"mnzores",
	"wonkyskeleton",
}

Assets = {
	Asset("IMAGE", "images/minimap/miner_minimap.tex"),
	Asset("ATLAS", "images/minimap/miner_minimap.xml"),
	Asset("IMAGE", "images/minimap/minerdestroyed_minimap.tex"),
	Asset("ATLAS", "images/minimap/minerdestroyed_minimap.xml"),
	Asset("IMAGE", "images/minimap/minerkit_minimap.tex"),
	Asset("ATLAS", "images/minimap/minerkit_minimap.xml"),
	
	Asset("SOUNDPACKAGE", "sound/miningmachine.fev"),
    Asset("SOUND", "sound/miningmachine_bank00.fsb"),
}

AddMinimapAtlas("images/minimap/miner_minimap.xml")
AddMinimapAtlas("images/minimap/minerdestroyed_minimap.xml")
AddMinimapAtlas("images/minimap/minerkit_minimap.xml")

local require = GLOBAL.require

require("mmloottable")

local STRINGS = GLOBAL.STRINGS
local RECIPETABS = GLOBAL.RECIPETABS
local Recipe = GLOBAL.Recipe
local GIngredient = GLOBAL.Ingredient
local TECH = GLOBAL.TECH

local FRAMES = GLOBAL.FRAMES
local ACTIONS = GLOBAL.ACTIONS
local State = GLOBAL.State
local EventHandler = GLOBAL.EventHandler
local ActionHandler = GLOBAL.ActionHandler
local TimeEvent = GLOBAL.TimeEvent
local EQUIPSLOTS = GLOBAL.EQUIPSLOTS

----------------------------------------------------MOD CONFIG PARAMS------------------------------------------------

GLOBAL.MMKINGREDIENTS = {}
GLOBAL.MMKINGREDIENTS["gears"] = GetModConfigData("MMKGEARSREQ")
GLOBAL.MMKINGREDIENTS["goldnugget"] = GetModConfigData("MMKGOLDREQ")
GLOBAL.MMKINGREDIENTS["boards"] = GetModConfigData("MMKBOARDSREQ")
GLOBAL.MMKINGREDIENTS["transistor"] = GetModConfigData("MMKDOODADSREQ")
local MMKTECHLEVEL = GetModConfigData("MMKTECHLEVEL")

local CWTWIGSREQ = GetModConfigData("CWTWIGSREQ")
local CWTROCKSREQ = GetModConfigData("CWTROCKSREQ")
local CWROPEREQ = GetModConfigData("CWROPEREQ")

local IWIRONREQ = GetModConfigData("IWIRONREQ")

GLOBAL.TUNING.IWDURABILITY = GetModConfigData("IWDURABILITY")

GLOBAL.TUNING.MMSTORAGESIZE = GetModConfigData("MMStorageSize")

GLOBAL.TUNING.CHESTMOBSODDS = GetModConfigData("ChestMobOdds")
GLOBAL.TUNING.ESCMOBSODDS = GetModConfigData("EscapeMobOdds")

GLOBAL.TUNING.DIGPERIOD = GetModConfigData("DIGPERIOD")
GLOBAL.TUNING.DIGSUCCESODDS = GetModConfigData("DIGSUCCESODDS")
GLOBAL.TUNING.JAMODDS = GetModConfigData("JAMODDS")
GLOBAL.TUNING.WINTERSLOWDOWN = GetModConfigData("WINTERSLOWDOWN")
GLOBAL.TUNING.SUMMERJAMINC = GetModConfigData("SUMMERJAMINC")
GLOBAL.TUNING.KEEPREMAINS = GetModConfigData("KEEPREMAINS")

local function ReturnTechLevel(modcfg)
	if modcfg == "NONE" then
		return TECH.NONE
	elseif modcfg == "SCIENCE_ONE" then
		return TECH.SCIENCE_ONE
	elseif modcfg == "SCIENCE_TWO" then
		return TECH.SCIENCE_TWO		
	elseif modcfg == "MAGIC_TWO" then
		return TECH.MAGIC_TWO			
	elseif modcfg == "MAGIC_THREE" then
		return TECH.MAGIC_THREE			
	end
end


--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

local MININGMACHINEKITrecipeIngredients = {}

for k, v in pairs(GLOBAL.MMKINGREDIENTS) do
	MININGMACHINEKITrecipeIngredients[#MININGMACHINEKITrecipeIngredients + 1]= GIngredient(k, v);
end

AddRecipe("miningmachinekit_item", MININGMACHINEKITrecipeIngredients , RECIPETABS.TOWN, ReturnTechLevel(MMKTECHLEVEL), nil, nil, nil, 1, nil, "images/inventory/miningmachinekit_item.xml", "miningmachinekit_item.tex")

local CRAPPYWRENCHrecipeIngredients = {}

CRAPPYWRENCHrecipeIngredients[#CRAPPYWRENCHrecipeIngredients + 1]= GIngredient("twigs", CWTWIGSREQ);
CRAPPYWRENCHrecipeIngredients[#CRAPPYWRENCHrecipeIngredients + 1]= GIngredient("rocks", CWTROCKSREQ);
CRAPPYWRENCHrecipeIngredients[#CRAPPYWRENCHrecipeIngredients + 1]= GIngredient("rope", CWROPEREQ);

AddRecipe("crappywrench", CRAPPYWRENCHrecipeIngredients , RECIPETABS.TOOLS, ReturnTechLevel(MMKTECHLEVEL), nil, nil, nil, 1, nil, "images/inventory/crappywrench.xml", "crappywrench.tex")

local IRONWRENCHrecipeIngredients = {}

IRONWRENCHrecipeIngredients[#IRONWRENCHrecipeIngredients + 1]= GIngredient("mnzironore", IWIRONREQ, "images/inventory/mnzironore.xml");


AddRecipe("ironwrench", IRONWRENCHrecipeIngredients , RECIPETABS.TOOLS, ReturnTechLevel(MMKTECHLEVEL), nil, nil, nil, 1, nil, "images/inventory/ironwrench.xml", "ironwrench.tex")

-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

STRINGS.NAMES.MININGMACHINEKIT_ITEM = "Mining Machine Kit"
STRINGS.RECIPE_DESC.MININGMACHINEKIT_ITEM = "Jury rigged Ikea"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MININGMACHINEKIT_ITEM = "I better get to building soon."

STRINGS.NAMES.MININGMACHINEKIT = "Mining Machine Kit"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MININGMACHINEKIT = "I better get to building soon."

STRINGS.NAMES.MININGMACHINE = "Mining Machine"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MININGMACHINE = {
	GENERIC = "It is more efficient if turned on...",
	JAMMED = "The ground has foiled me.",
	MINING = "I wonder what it will dig up.",
	NOFUEL = "Like me, it's not working with an empty belly.",
}

STRINGS.NAMES.MININGMACHINE_DESTROYED = "Mining Machine Remains"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MININGMACHINE_DESTROYED = "It won't dig much now..."

STRINGS.NAMES.MININGMACHINE_STORAGE = "Mining Machine Storage"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MININGMACHINE_STORAGE = "Which surprises are waiting for me in here?"

STRINGS.NAMES.CRAPPYWRENCH = "Wooden wrench"
STRINGS.RECIPE_DESC.CRAPPYWRENCH = "Arguable quality"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.CRAPPYWRENCH = "A jury rigged wrench"

STRINGS.NAMES.IRONWRENCH = "Iron Wrench"
STRINGS.RECIPE_DESC.IRONWRENCH = "A bit more solid"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.IRONWRENCH = "Something a bit more solid"

STRINGS.NAMES.MNZIRONORE = "Iron Ore"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MNZIRONORE = "It might be dull, but it's useful"

STRINGS.NAMES.WONKYSKELETON = "Wonky Skeleton"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.WONKYSKELETON = "I guess I should be careful where I place my devices next time."

-----------------------------------------------------------------------ACTIONS--------------------------------------------------------------------------------------------------------

local REPAIRMM = GLOBAL.Action(	6,		-- priority
								nil,	-- instant (set to not instant)
								nil,	-- right mouse button
								nil,	-- distance check
								nil,	-- ghost valid (set to not ghost valid)
								nil,	-- ghost exclusive
								nil,	-- can force action
								nil)	-- Range check function
REPAIRMM.strfn = function(act)
	local target = act.target
	local invobject = act.invobject
	if target:HasTag("jammed") then
		return "UNJAM"
	elseif target:HasTag("kit") then
		return "MOUNT"
	elseif invobject.prefab == "miningmachinekit_item" and target.prefab == "miningmachine_destroyed" then
		return "REBUILD"
	end
end
REPAIRMM.id = "REPAIRMM"
REPAIRMM.fn = function(act)
	local target = act.target
	local invobj = act.invobject

	if invobj.prefab == "miningmachinekit_item" and target.prefab == "miningmachine_destroyed" then
		GLOBAL.SpawnPrefab("collapse_small").Transform:SetPosition(target.Transform:GetWorldPosition())
		
		local ruinspos = target:GetPosition()
		target:Remove()
		invobj:Remove()
		
		local newmachine = GLOBAL.SpawnPrefab("miningmachine")
		newmachine.Transform:SetPosition(ruinspos:Get())
		return true
	end
	
	-- print("target is ", target or "UNAVAILABLE", "and invobj is ", invobj or "UNAVAILABLE")
	-- print("target is jammed : ", target:HasTag("jammed"), " | target is artificially in cooldown : ", target:HasTag("cooldown"))
	if invobj and target and target:HasTag("jammed") then
		-- print("I unjam the machine!")
		target.components.mnzmachines.jammed = false
		if invobj.components.finiteuses then invobj.components.finiteuses:Use() end
		return true
	end
	
	if invobj and target and target:HasTag("kit") and target:HasTag("structure") then
		-- print("I mount the machine!")
		local targetx, targety, targetz = target.Transform:GetWorldPosition()
		GLOBAL.SpawnPrefab("collapse_small").Transform:SetPosition(targetx, targety, targetz)
		local mountedmachine = GLOBAL.SpawnPrefab("miningmachine")
		
		if target.area then 
			-- print("I mounted the mining machine next to a special area : ", target.area)
			mountedmachine.area = target.area
		end
		target:Remove()
		
		mountedmachine.Transform:SetPosition(targetx, targety, targetz)
		
		if invobj.components.finiteuses then invobj.components.finiteuses:Use() end
		return true
	end
	

end

AddAction(REPAIRMM)

local ADDSPECIALFULEMM = GLOBAL.Action(	6,		-- priority
								nil,	-- instant (set to not instant)
								nil,	-- right mouse button
								nil,	-- distance check
								nil,	-- ghost valid (set to not ghost valid)
								nil,	-- ghost exclusive
								nil,	-- can force action
								nil)	-- Range check function
ADDSPECIALFULEMM.strfn = function(act)
	if act.invobject.prefab == "mole" then
		return "ADDMOLE"
	end
end
ADDSPECIALFULEMM.id = "ADDSPECIALFULEMM"
ADDSPECIALFULEMM.fn = function(act)
    if act.doer.components.inventory then
        local fuel = act.doer.components.inventory:RemoveItem(act.invobject)
        if fuel then
            if act.target.components.mnzmachines:TakeSpecialFuelItem(fuel) then
                return true
            else
                --print("False")
                act.doer.components.inventory:GiveItem(fuel)
            end
        end
    end
end

AddAction(ADDSPECIALFULEMM)

AddStategraphActionHandler("wilson", ActionHandler(ACTIONS.REPAIRMM, "dolongaction"))
AddStategraphActionHandler("wilson_client", ActionHandler(ACTIONS.REPAIRMM, "dolongaction"))

AddStategraphActionHandler("wilson", ActionHandler(ACTIONS.ADDSPECIALFULEMM, "doshortaction"))
AddStategraphActionHandler("wilson_client", ActionHandler(ACTIONS.ADDSPECIALFULEMM, "doshortaction"))

local function MnZEquippedCA(inst, doer, target, actions, right)
    if inst:HasTag("MnZmachines") and inst:HasTag("wrench") and target:HasTag("MnZmachines") and
		(target:HasTag("jammed") or (target:HasTag("kit") and target:HasTag("structure")))
		then
			table.insert(actions, ACTIONS.REPAIRMM)
	end
end

local function MnZUseitemCA(inst, doer, target, actions, right)
	if inst.prefab == "mole" and target:HasTag("MnZmachines") and not target:HasTag("kit") then
		table.insert(actions, ACTIONS.ADDSPECIALFULEMM)
    elseif inst:HasTag("MnZmachines") and inst:HasTag("wrench") and target:HasTag("MnZmachines") and
		(target:HasTag("jammed") or (target:HasTag("kit") and target:HasTag("structure")))
		then
			table.insert(actions, ACTIONS.REPAIRMM)
	elseif inst.prefab == "miningmachinekit_item" and target.prefab == "miningmachine_destroyed" then
			table.insert(actions, ACTIONS.REPAIRMM)
	end
end

AddComponentAction("EQUIPPED", "mnzmachines", MnZEquippedCA)
AddComponentAction("USEITEM", "mnzmachines", MnZUseitemCA)

GLOBAL.STRINGS.ACTIONS["REPAIRMM"] = {
	UNJAM = "Unjam the Mining Machine",
	MOUNT = "Mount the Mining Machine",
	REBUILD = "Raise a new Mining Machine from these remains",
}

GLOBAL.STRINGS.ACTIONS["ADDSPECIALFULEMM"] = {
	ADDMOLE = "Add High Octane Fuel",
}

local base_deploystrfn = ACTIONS.DEPLOY.strfn

ACTIONS.DEPLOY.strfn = function(act)
	return act.invobject~= nil and
			(act.invobject:HasTag("MnZmachines") and act.invobject:HasTag("kit") and "MMKIT") or
			base_deploystrfn(act)
end

GLOBAL.STRINGS.ACTIONS.DEPLOY["MMKIT"] = "Deploy the Mining Machine Kit"

AddPrefabPostInit("mole", function(prefab)
							prefab:AddComponent("mnzmachines")	
						end
)

AddModRPCHandler("Mining Machine", "SpawnSurpriseLoot", function(player, storage, surprise)
															local surprisemob = GLOBAL.SpawnPrefab(surprise)
															surprisemob.Transform:SetPosition(storage.Transform:GetWorldPosition())
														end
)
