--[[ add Bale Types

	Author: 	Ifko[nator]
	Datum: 		08.08.2015
	Version: 	1.5

	History: 	V 0.5 @ 13.04.2015 - intial release - BETA - added: Baleregister function, witch is defined in the modDesc. So u can add new baleTypes without touch this Script.
				V 0.8 @ 19.04.2015 - added: Function for add Baler Fill Types. It will the fillTypes, they are given to the parameter 'windrowsAddToBalers' in the modDesc.
				V 0.9 @ 21.04.2015 - added: FSBaseMission.loadMap function, to check if windrows are avaiable or not. If they not avaiable, the Bales will be not registered and the FillTypes not added to the Balers!
				V 1.0 @ 23.04.2015 - last fixes.
				v 1.1 @ 10.05.2015 - added support for Balewrappers. Now it will loaded the correct grass roundbale, if you wrap an grass roundbale and you don't use the 'BaleExtension' Mod. 
									 If you use the 'BaleExtension' Mod, his grass roundbale will loaded instead of my grass roundbale. (Because, his grass roundbale will then dropped from the Baler, not my ..)
				V 1.5 @ 08.08.2015 - fix for bale load from mod balers, if mod directory is not the orginal and FINALLY public release.

	Dieses Script fügt allen Ballenpressen, die auf dem Standard 'Baler' Script laufen, neue Ballen- und Fülltypen hinzu, sofern die Früchte auch auf der Map vorhanden sind! Das ist komplett in der modDesc dieser addBaleTypes.zip konfigurierbar. 
	Dadurch muss man nichts im Script ändern, wenn man Ballen für neue Schwaden hinzufügen will. 
	
	Es ist bereits alles für: 
	
	- Gras (grass_windrow)
	- Roggen (rye_windrow)
	- Hafer (oat_windrow)
	- Triticale (triticale_windrow)
	- Hirse (millet_windrow)
	- Dinkel (dinkel_windrow)

	vorbereitet. Die Fülltypen, die in der modDesc im Parameter 'windrowsAddToBalers' angegeben werden, werden den Pressen hinzugefügt. 
	Dieses Script registriert Grasrundballen nur dann, wenn der 'BaleExtension' Mod von Upsidedown nicht vorhanden ist, da es sonst sein Mod schon macht. 
	Quaderballen werden immer registriert, sofern die Map auch den Schwad verbaut hat. Man kann auch den Pfad zu den Ballen in der modDesc anpassen, ('filename="bla/bla/bla.i3d"').
	
	
	Fix ab V 1.1:
	
	Unterstüzung für Ballenwickler hinzugefügt: 
	
	- Es wird nun der korrekte Grasrundballen auf den Wickler geladen, wenn nicht der 'BaleExtension' Mod genutzt wird. 
	  Sollte der 'BaleExtension' Mod genutzt werden, wird dessen Grasrundballen auf den Wickler geladen. (Da dann auch sein Grasrundballen von der Presse ausgeworfen wird und nicht meiner ..)
]]

local addBaleTypesDirectory = g_currentModDirectory;

--print("Path to the addBaleTypes.zip: " .. tostring(addBaleTypesDirectory));

local modDesc = loadXMLFile("modDesc", addBaleTypesDirectory .. "modDesc.xml");
local version = getXMLString(modDesc, "modDesc.version");

local newSquareBaleFilename = Utils.getFilename("bales/squarebales/baleStraw240.i3d", addBaleTypesDirectory);
local newRoundBaleFilename = Utils.getFilename("bales/roundbales/roundbaleStraw_w112_d130.i3d", addBaleTypesDirectory);
local newSilageRoundBaleFilename = Utils.getFilename("bales/roundbales/roundbaleSilage_w112_d130.i3d", addBaleTypesDirectory);

local allowOverrideOriginalStrawBales = Utils.getNoNil(getXMLBool(modDesc, "modDesc.addBaleTypes#allowOverrideOriginalStrawBales"), true);
local allowDebugPrint = Utils.getNoNil(getXMLBool(modDesc, "modDesc.addBaleTypes#allowDebugPrint"), false);

local currentMap = "Unknown";

print("### addBaleTypes Script by Ifko[nator] in der Version: '" .. version .. "' erfolgreich geladen!");

local oldFSBaseMission_loadMap = FSBaseMission.loadMap;
FSBaseMission.loadMap = function(a, b, c, d, e)
	local bales = 0;

	currentMap = a.missionInfo.map.title;
	
	while true do
		local baseName = string.format("modDesc.addBaleTypes.addBaleType(%d)", bales);
		
		if not hasXMLProperty(modDesc, baseName) then
			break;
		end
	
		local filename = getXMLString(modDesc, baseName .. "#filename");
		local windrow = getXMLString(modDesc, baseName .. "#windrow");
		
		if filename ~= (nil and "") then
			local filenameForMod = Utils.getFilename(filename, addBaleTypesDirectory);
			
			if string.find(filename, "$data") then
				filename = filename;
			else
				filename = filenameForMod;
			end;
			
			local isRoundbale = Utils.getNoNil(getXMLBool(modDesc, baseName .. "#isRoundbale"), false);
			local width = Utils.round(Utils.getNoNil(getXMLFloat(modDesc, baseName .. "#width"), 1.2), 2);
			local height = Utils.round(Utils.getNoNil(getXMLFloat(modDesc, baseName .. "#height"), 0.9), 2);
			local length = Utils.round(Utils.getNoNil(getXMLFloat(modDesc, baseName .. "#width"), 2.4), 2);
			local diameter = Utils.round(Utils.getNoNil(getXMLFloat(modDesc, baseName .. "#diameter"), 1.8), 2);
			
			if windrow ~= (nil and "") then
				local fruittype = "FRUITTYPE_" .. string.upper(windrow);
				windrow = windrow .. "_windrow";
				
				local checkWindrow = Fillable.fillTypeNameToInt[windrow];
				local baletype = BaleUtil.getBaleKey(windrow, width, height, length, diameter, isRoundbale);
				
				if checkWindrow ~= nil then
					if isRoundbale then
						if g_modNameToDirectory["ZZZ_baleExtension"] then
							if windrow == "grass_windrow" then
								print("----------------------------------------------------------------------------------------------[INFO from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
								print("'BaleExtension' Mod by Upsidedown found! Roundbales for 'grass_windrow' will be not registered from this Script!");
								print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
							else
								BaleUtil.registerBaleType(filename, windrow, width, nil, nil, diameter, true);
								if allowDebugPrint then
									print("----------------------------------------------------------------------------------------------[DEBUG from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
									print("Register Roundbale for: '" .. windrow .. "' with width: '" .. width .. "' and diameter: '" .. diameter .. "' successfully.");
									print("Filename = '" .. filenameForMod .. "'.");
									print("Baletype = '" .. baletype .. "'.");
									print("Fruittype = '" .. fruittype .. "'.");
									print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
								end;
							end;
						else
							BaleUtil.registerBaleType(filename, windrow, width, nil, nil, diameter, true);
							if allowDebugPrint then
								print("----------------------------------------------------------------------------------------------[DEBUG from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
								print("Register Roundbale for: '" .. windrow .. "' with width: '" .. width .. "' and diameter: '" .. diameter .. "' successfully.");
								print("Filename = '" .. filenameForMod .. "'.");
								print("Baletype = '" .. baletype .. "'.");
								print("Fruittype = '" .. fruittype .. "'.");
								print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
							end;
						end;
					else
						BaleUtil.registerBaleType(filename, windrow, width, height, length, nil, false);
						if allowDebugPrint then
							print("----------------------------------------------------------------------------------------------[DEBUG from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
							print("Register Squarebale for: '" .. windrow .. "' wtih width: '" .. width .. "', height: '" .. height .. "' and length: '" .. length .. "' successfully.");
							print("Filename = '" .. filenameForMod .. "'.");
							print("Baletype = '" .. baletype .. "'.");
							print("Fruittype = '" .. fruittype .. "'.");
							print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
						end;
					end;
				else
					if isRoundbale then
						if allowDebugPrint then
							print("----------------------------------------------------------------------------------------------[DEBUG from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
							print("[Roundbale]: '" .. windrow .. "' is not avaiable on the '" .. currentMap .. "' Map! This Bale will be not registered from this Script!");
							print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
						end;
					else
						if allowDebugPrint then
							print("----------------------------------------------------------------------------------------------[DEBUG from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
							print("[Squarebale]: '" .. windrow .. "' is not avaiable on the '" .. currentMap .. "' Map! This Bale will be not registered from this Script!");
							print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
						end;
					end;
				end;
			else
				local bale = bales + 1;
				
				if isRoundbale then
					print("----------------------------------------------------------------------------------------------[ERROR from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
					print("[Roundbale]: No windrow is given to Bale number '" .. bale .. "'. This Bale will be not registered from this Script!");
					print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
				else
					print("----------------------------------------------------------------------------------------------[ERROR from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
					print("[Squarebale]: No windrow is given to Bale number '" .. bale .. "'. This Bale will be not registered from this Script!");
					print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
				end;
			end;
		else
			local bale = bales + 1;
		
			if isRoundbale then
				print("----------------------------------------------------------------------------------------------[ERROR from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
				print("[Roundbale]: No filename is given to Bale number '" .. bale .. "'. This Bale will be not registered from this Script!");
				print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
			else
				print("----------------------------------------------------------------------------------------------[ERROR from the addBaleTypes.lua]-----------------------------------------------------------------------------------------------");
				print("[Squarebale]: No filename is given to Bale number '" .. bale .. "'. This Bale will be not registered from this Script!");
				print("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
			end;
		end;
		bales = bales + 1;
	end;
	
	ra, rb, rc, rd, re = oldFSBaseMission_loadMap(a, b, c, d, e);
	
	return ra, rb, rc, rd, re;
end;

--## Double Filename fix for mod balers. Inspired from the 'BaleExtension' Mod by Upsidedown.
local fixLoadSharedI3DFile = Utils.loadSharedI3DFile;
function Utils.loadSharedI3DFile(filename, baseDir, ...)
	local pos = string.find(filename, ":/", 1);
	if pos ~= nil then	
		baseDir = "";
	end;
	
	pos = string.find(filename, ":/", 3);
	
	if pos ~= nil then		
		filename = string.sub(filename, pos - 1);
	end;
	
	pos = string.find(filename, "/addBaleTypes/bales/");
	if pos ~= nil then
		if not fileExists(Utils.getNoNil(baseDir, "") .. filename) then
			baseDir = "";
			filename = g_modsDirectory .. string.sub(filename, pos + 1);
		end;
	end;
	
	local fixedFilename = fixLoadSharedI3DFile(filename, baseDir, ...);

	return fixedFilename;
end;


local oldloadSharedI3DFile = Utils.loadSharedI3DFile;
Utils.loadSharedI3DFile = function (filename, baseDir, ...)
	if allowOverrideOriginalStrawBales then
		if filename == "$data/maps/models/objects/squarebales/baleStraw240.i3d" then
			filename = newSquareBaleFilename;
		elseif filename == "$data/maps/models/objects/roundbales/roundbaleStraw_w112_d130.i3d" then
			filename = newRoundBaleFilename;
		end;
	else
		if filename == newSquareBaleFilename then
			filename = "$data/maps/models/objects/squarebales/baleStraw240.i3d";
		elseif filename == newRoundBaleFilename then
			filename = "$data/maps/models/objects/roundbales/roundbaleStraw_w112_d130.i3d";
		end;
	end;
	
	if not g_modNameToDirectory["ZZZ_baleExtension"] then
		if filename == "$data/maps/models/objects/roundbales/roundbaleSilage_w112_d130.i3d" then
			filename = newSilageRoundBaleFilename;
		end;
	else
		if filename == (newSilageRoundBaleFilename or "$data/maps/models/objects/roundbales/roundbaleSilage_w112_d130.i3d") then
			filename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleSilage_w112_d130.i3d";
		end;
		
		if filename == "$data/maps/models/objects/roundbales/roundbaleHay_w112_d130.i3d" then
			filenename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleHay_w112_d130.i3d";
		end;
		
		if filename == g_modsDirectory .. "/addBaleTypes/bales/roundbales/roundbaleGrass_w112_d130.i3d" then
			filename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleGrass_w112_d130.i3d";
		end;
	end;
	
	local baleFilename = oldloadSharedI3DFile(filename, baseDir, ...);
	
	return baleFilename;
end;

Bale.load = function (self, i3dFilename, x, y, z, rx, ry, rz, fillLevel)
	if allowOverrideOriginalStrawBales then
		if i3dFilename == "data/maps/models/objects/squarebales/baleStraw240.i3d" then
			i3dFilename = newSquareBaleFilename;
		elseif i3dFilename == "data/maps/models/objects/roundbales/roundbaleStraw_w112_d130.i3d" then
			i3dFilename = newRoundBaleFilename;
		end;
	else
		if i3dFilename == newSquareBaleFilename then
			i3dFilename = "data/maps/models/objects/squarebales/baleStraw240.i3d";
		elseif i3dFilename == newRoundBaleFilename then
			i3dFilename = "$data/maps/models/objects/roundbales/roundbaleStraw_w112_d130.i3d";
		end;
	end;
	
	if not g_modNameToDirectory["ZZZ_baleExtension"] then
		if i3dFilename == "$data/maps/models/objects/roundbales/roundbaleSilage_w112_d130.i3d" then
			i3dFilename = newSilageRoundBaleFilename;
		end;
	else
		if i3dFilename == (newSilageRoundBaleFilename or "data/maps/models/objects/roundbales/roundbaleSilage_w112_d130.i3d") then
			i3dFilename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleSilage_w112_d130.i3d";
		end;
		
		if i3dFilename == "$data/maps/models/objects/roundbales/roundbaleHay_w112_d130.i3d" then
			i3dFilename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleHay_w112_d130.i3d";
		end;
		
		if i3dFilename == g_modsDirectory .. "/addBaleTypes/bales/roundbales/roundbaleGrass_w112_d130.i3d" then
			i3dFilename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleGrass_w112_d130.i3d";
		end;
	end;
	
	self.i3dFilename = i3dFilename;
	self.customEnvironment, self.baseDirectory = Utils.getModNameAndBaseDirectory(i3dFilename);

	self.createNode(self, i3dFilename);
	setTranslation(self.nodeId, x, y, z);
	setRotation(self.nodeId, rx, ry, rz);

	if fillLevel ~= nil then
		self.fillLevel = fillLevel;
	end;

	g_currentMission:addItemToSave(self);

	return true;
end;

Bale.loadFromAttributesAndNodes = function (self, xmlFile, key, resetVehicles)
	local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, key .. "#position"));
	local xRot, yRot, zRot = Utils.getVectorFromString(getXMLString(xmlFile, key .. "#rotation"));

	if (x or y or z or xRot or yRot or zRot) == nil then
		return false;
	end;

	local filename = getXMLString(xmlFile, key .. "#filename");

	if filename == nil then
		return false;
	end;

	if allowOverrideOriginalStrawBales then
		if filename == "data/maps/models/objects/squarebales/baleStraw240.i3d" then
			filename = newSquareBaleFilename;
		elseif filename == "data/maps/models/objects/roundbales/roundbaleStraw_w112_d130.i3d" then
			filename = newRoundBaleFilename;
		end;
	else
		if filename == newSquareBaleFilename then
			filename = "data/maps/models/objects/squarebales/baleStraw240.i3d";
		elseif filename == newRoundBaleFilename then
			filename = "data/maps/models/objects/roundbales/roundbaleStraw_w112_d130.i3d";
		end;
	end;
	
	if not g_modNameToDirectory["ZZZ_baleExtension"] then
		if filename == "data/maps/models/objects/roundbales/roundbaleSilage_w112_d130.i3d" then
			filename = newSilageRoundBaleFilename;
		end;
	else
		if filename == (newSilageRoundBaleFilename or "data/maps/models/objects/roundbales/roundbaleSilage_w112_d130.i3d") then
			filenename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleSilage_w112_d130.i3d";
		end;
		
		if filename == "data/maps/models/objects/roundbales/roundbaleHay_w112_d130.i3d" then
			filenename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleHay_w112_d130.i3d";
		end;
		
		if filename == g_modsDirectory .. "/addBaleTypes/bales/roundbales/roundbaleGrass_w112_d130.i3d" then
			filename = g_modsDirectory .. "/ZZZ_baleExtension/bales/roundbaleGrass_w112_d130.i3d";
		end;
	end;
	
	filename = Utils.convertFromNetworkFilename(filename);
	local rootNode = Utils.loadSharedI3DFile(filename);

	if rootNode == 0 then
		return false;
	end;

	local ret = false;
	local node = getChildAt(rootNode, 0);

	if node ~= nil and node ~= 0 then
		setTranslation(node, x, y, z);
		setRotation(node, xRot, yRot, zRot);
		link(getRootNode(), node);

		ret = true;
	end;

	delete(rootNode);

	if not ret then
		return false;
	end;

	self.loadFromMemory(self, node, filename);

	local fillLevel = getXMLFloat(xmlFile, key .. "#fillLevel");

	if fillLevel ~= nil then
		self.fillLevel = fillLevel;
	end;

	if self.supportsWrapping then
		self.wrappingState = Utils.getNoNil(getXMLFloat(xmlFile, key .. "#wrappingState"), 0);
		setShaderParameter(self.baleMesh, "wrappingState", self.wrappingState, 0, 0, 0, false);
	end;

	local baleValueScale = Utils.getNoNil(tonumber(getXMLString(xmlFile, key .. "#baleValueScale")), 1);

	self.baleValueScale = baleValueScale;

	return true;
end;

local oldBalerLoad = Baler.load;
Baler.load = function (self, xmlFile)
	oldBalerLoad(self, xmlFile);
	
	local windrowsAddToBalers = getXMLString(modDesc, "modDesc.addBaleTypes#windrowsAddToBalers");
	
	if windrowsAddToBalers ~= nil then
		local windrows = Utils.splitString(" ", windrowsAddToBalers);
		
		for k, windrow in pairs(windrows) do
			windrow = windrow .. "_windrow"
			local windrowToAdd = Fillable.fillTypeNameToInt[windrow];
			
			if windrowToAdd ~= nil then
				if self.fillTypes[windrowToAdd] == nil then
					self.fillTypes[windrowToAdd] = true;
					if allowDebugPrint then
						print("[DEBUG from the addBaleTypes.lua]: '" .. windrow .. "' was added to: '" .. self.configFileName .. "'.");
					end;
				else
					if allowDebugPrint then
						print("[DEBUG from the addBaleTypes.lua]: '" .. windrow .. "' is already exists and was not added to: '" .. self.configFileName .. "'.");
					end;
				end;
			else
				if allowDebugPrint then
					print("[DEBUG from the addBaleTypes.lua]: '" .. windrow .. "' is not avaiable on the '" .. currentMap .. "' Map and was not added to: '" .. self.configFileName .. "'.");
				end;
			end;
		end;
	end;
end;

--[[ ## This is not Working! :(
local oldWindrowerLoad = Windrower.load;
Windrower.load = function (self, xmlFile)
	oldWindrowerLoad(self, xmlFile);

	if self.windrowerParticleSystems ~= nil then
		local grass_windrow1 = Fillable.fillTypeNameToInt["grass_windrow"];
		local klee_windrow1 = Fillable.fillTypeNameToInt["klee_windrow"];
		
		local grass_windrow = FruitUtil.fillTypeToFruitType[grass_windrow1];
		local klee_windrow = FruitUtil.fillTypeToFruitType[klee_windrow1];
		
		for psNumber, ps in pairs(self.windrowerParticleSystems) do
			if ps.fruitType ~= nil then
				print(":: DEBUG from the addBaleTypes.lua: ps.fruitType ~= nil! :O");
				print(":: DEBUG from the addBaleTypes.lua: grass_windrow is: '" .. grass_windrow .. "'.");
				
				if ps.fruitType == grass_windrow then --FruitUtil.FRUITTYPE_GRASS_WINDROW then
					print(":: DEBUG from the addBaleTypes.lua: Found GRASS_WINDROW PS Number: '" .. psNumber .. "'!");
					--## Okay, this is workig, but HOW give i the grass PS to luzerne and klee ??? Crap ..
					
					print(":: DEBUG from the addBaleTypes.lua: windrowerParticleSystems grass_windrow is: '" .. Utils.getNoNil(tostring(self.windrowerParticleSystems[grass_windrow]), "nil") .. "'!");
					
					if klee_windrow1 ~= nil then
						--if self.windrowerParticleSystems[klee_windrow] == nil then
							self.windrowerParticleSystems[klee_windrow] = self.windrowerParticleSystems[grass_windrow];
							print(":: DEBUG from the addBaleTypes.lua: Set windrower particle system for klee in: '" .. self.configFileName .. "'.");
							--## Nope, still not Working .. Crap .. bullshit ..
							print(":: DEBUG from the addBaleTypes.lua: windrowerParticleSystems klee_windrow is: '" .. Utils.getNoNil(tostring(self.windrowerParticleSystems[klee_windrow]), "nil") .. "'!");
						--end;
					else
						print(":: DEBUG from the addBaleTypes.lua: Not found klee on: '" .. currentMap .. "'.");
					end;
				end;
			else
				print(":: DEBUG from the addBaleTypes.lua: ps.fruitType == nil! :( Next try, please!");
			end;
		end;
	end;
end;]]
