--
-- New Holland BB9090
--
-- author  Mythos
-- date  20/06/2011
-- www.ARM-team.gr
-- Copyright (C) ARM Team, All Rights Reserved.

BB9090 = {};
--________________________________________________________________________________________________________________________________________________________
function BB9090.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Fillable, specializations);
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:load(xmlFile)

	-- Functions
	self.getIsAreaActive = Utils.overwrittenFunction(self.getIsAreaActive, BB9090.getIsAreaActive);
	--self.baleCounter = Utils.overwrittenFunction(self.getIsAreaActive, BB9090.baleCounter);
	self.baleCounter= SpecializationUtil.callSpecializationsFunction("baleCounter");
	self.WorkBB9090= SpecializationUtil.callSpecializationsFunction("WorkBB9090");
	self.pickUpMode= SpecializationUtil.callSpecializationsFunction("pickUpMode");
	self.BLightBB9090= SpecializationUtil.callSpecializationsFunction("BLightBB9090");

	self.TimeSet= SpecializationUtil.callSpecializationsFunction("TimeSet");
	self.DroppBale= SpecializationUtil.callSpecializationsFunction("DroppBale");
	self.UnloadBB9090= SpecializationUtil.callSpecializationsFunction("UnloadBB9090");
	self.EmptyBB9090= SpecializationUtil.callSpecializationsFunction("EmptyBB9090");
	
	-- Animations
	self.workAnim = getXMLString(xmlFile, "vehicle.chute#animationName");
	self.pickUpAnim = getXMLString(xmlFile, "vehicle.pickUp#animationName");

	-- Indexs
	self.roller = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.roller#index"));
	self.backLight = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.backLight#index"));
	self.backCone = Utils.indexToObject(self.components,getXMLString(xmlFile,"vehicle.backCone#index"));
	
	-- Particles
	self.bbParticles = {};
	local i = 0;
    while true do
        local key = string.format("vehicle.bbParticles.pSystem(%d)", i);
		local node = Utils.indexToObject(self.components, getXMLString(xmlFile, key.. "#index"));
		if node == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.bbParticles, key, node, false, nil, self.baseDirectory)		
		i = i +1;		
    end;
	
	-- Booleans
	self.workPos = false;
	self.pickUpPos = false;
	self.previousLevel = 0;
	self.backLightStatus = false;
	self.GTA = false;
	self.unloadBales = false;
	self.emptyBaler = false;
	self.allowTransport = true;
	self.wrongSpeed = false;
	
	-- GTA Console
	self.file = Utils.getFilename("GTAConsole.png", self.baseDirectory);
	self.GTAx = 0.5;
    self.GTAy = 0.809;
    self.GTAWidth = 0.257;
    self.GTAHeight = 0.171;
	
	self.cX = 0.606;
    self.cY = 0.882;
	self.tX = 0.606;
    self.tY = 0.849;
	self.BBCurrent = 0;
	self.BBTotal = 0;
    
	self.BBGTA = Overlay:new("BBGTA", self.file, self.GTAx, self.GTAy, self.GTAWidth, self.GTAHeight);
	
	self.ct = 2000;

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:delete()
	Utils.deleteParticleSystem(self.bbParticles);
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:onDetach()
	setVisibility(self.backLight, false);
	setVisibility(self.backCone, false);
	self.backLightStatus = false;
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:mouseEvent(posX, posY, isDown, isUp, button)

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:keyEvent(unicode, sym, modifier, isDown)

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:update(dt)

	if self:getIsActiveForInput() and self:getIsActive() then
		
		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) then
			if not self.workPos then
				self.isTurnedOn = false;
			end;
		end;
		
		if (not self.isTurnedOn) and (not self.pickUpPos) and self.allowTransport then
			if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA2) then
				self.workPos = not self.workPos;
				self:WorkBB9090(self.workPos);
			end;
		end;
		
		if not self.allowTransport and not self.isTurnedOn and self.workPos and not self.emptyBaler and not self.unloadBales then
			if InputBinding.hasEvent(InputBinding.ALLOW_TRANSPORT) then
				self.unloadBales = true;
			end;
		end;
		
		
		if table.getn(self.bales) ~=0 and not self.isTurnedOn and self.workPos and not self.emptyBaler and not self.unloadBales then
			if InputBinding.hasEvent(InputBinding.EMPTY_BALER) then
				if self.lastSpeed*3600 < 13 then
					self.wrongSpeed = true;
				else
					self.emptyBaler = true;
				end;
			end;
		end;
		
		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA3) then
			self.GTA = not self.GTA;
		end;
		
		if InputBinding.hasEvent(InputBinding.BB9090BLIGHT) then
			self:BLightBB9090(not self.backLightStatus);
		end;
		
		if self.workPos then
			if InputBinding.hasEvent(InputBinding.LOWER_IMPLEMENT) then
				self:pickUpMode(not self.pickUpPos);
			end;
		end;
		
		if not self.emptyBaler then
			if table.getn(self.bales) ~=0 then
				for i,v in pairs(self.bales) do
					if v.time >0.466 then
						self.allowTransport = false;
						break;
					else
						self.allowTransport = true;
						self.unloadBales = false;
					end;
				end;
			else
				self.allowTransport = true;
				self.unloadBales = false;
			end;
		end;

--________________________________________________________________________________________________________________________________________________________
		if self.wrongSpeed then
			self.ct = self.ct - dt;
			if self.ct <0 then
				self.wrongSpeed = false;
				self.ct = 2000;
			end;
		end;
		
	end;
	
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:updateTick(dt)
	if self:getIsActive() then		
		
		if self.isTurnedOn and self.workPos then
			rotate(self.roller, dt*-0.01, 0, 0);
			if self.previousLevel ~= self.fillLevel then
				Utils.setEmittingState(self.bbParticles, true);
				self.previousLevel = self.fillLevel;
			else
				Utils.setEmittingState(self.bbParticles, false);
			end;
		else
			Utils.setEmittingState(self.bbParticles, false);
		end;
		
		if self.unloadBales then
			self:UnloadBB9090(self.unloadBales);
		end;
		
		if self.emptyBaler then
			self:EmptyBB9090(self.emptyBaler);
		end;
		
		for i, v in pairs(self.componentJoints) do
			setJointFrame(self.componentJoints[i].jointIndex, 0, self.componentJoints[i].jointNode);
		end;
		
	end;

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:draw()
			
		if not self.workPos then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("WORKMODE"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA2);
		elseif not self.isTurnedOn and not self.pickUpPos and self.allowTransport then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("TRANSPORTMODE"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA2);
		end;
		
		if self.workPos then
			if not self.pickUpPos then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("PICKUP_DOWN"), self.typeDesc), InputBinding.LOWER_IMPLEMENT);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("PICKUP_UP"), self.typeDesc), InputBinding.LOWER_IMPLEMENT);
			end;
		end;
		
		if self.GTA then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("CONSOLE_OFF"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA3);
		else
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("CONSOLE_ON"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA3);
		end;
		
		if self.backLightStatus then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("BACKLIGHT_OFF"), self.typeDesc), InputBinding.BB9090BLIGHT);
		else
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("BACKLIGHT_ON"), self.typeDesc), InputBinding.BB9090BLIGHT);
		end;
		
		if self.GTA then
			self.BBGTA:render();
			setTextBold(true);
			setTextColor(0, 0, 0, 1.0);
			renderText(self.cX, self.cY, 0.020, string.format(self.BBCurrent));
			renderText(self.tX, self.tY, 0.020, string.format(self.BBTotal));
		end;

		if not self.allowTransport and not self.isTurnedOn and self.workPos and not self.emptyBaler and not self.unloadBales then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("UNLOAD_BALES"), self.typeDesc), InputBinding.ALLOW_TRANSPORT);
		end;
		
		
		if table.getn(self.bales) ~=0 and not self.isTurnedOn and self.workPos and not self.emptyBaler and not self.unloadBales then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("EMPTY_BALER"), self.typeDesc), InputBinding.EMPTY_BALER);
		end;
		
		if self.wrongSpeed then
			g_currentMission:addWarning("You must have at least 13mph".."\n".."to complete this operation", 0.07+0.022);
		end;
		
end;

--______________________________________________________________________________________________________________________________________________________
function BB9090:BLightBB9090(mode, noEventSend)
	BLightBB9090Event.sendEvent(self, mode, noEventSend);
	
	if self:getIsActiveForSound() and mode then
		setVisibility(self.backLight, true);
		setVisibility(self.backCone, false);
		self.backLightStatus = true;
	elseif not self:getIsActiveForSound() and mode then
		setVisibility(self.backLight, false);
		setVisibility(self.backCone, true);
		self.backLightStatus = false;
	else
		setVisibility(self.backLight, false);
		setVisibility(self.backCone, false);
		self.backLightStatus = false;
	end;

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:WorkBB9090(mode,noEventSend)
	WorkBB9090Event.sendEvent(self, mode, noEventSend);
	
	if mode then
		self:playAnimation(self.workAnim, 1, nil, true);
		self.workPos = true;
	else
		self:playAnimation(self.workAnim, -1, nil, true);
		self.workPos = false;
		self.allowTransport = true;
	end;

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:pickUpMode(mode,noEventSend)
	pickUpBB9090Event.sendEvent(self, mode, noEventSend);
		
	if mode then
		self:playAnimation(self.pickUpAnim, 1, nil, true);
		self.pickUpPos = true;
	else
		self:playAnimation(self.pickUpAnim, -1, nil, true);
		self.pickUpPos = false;
	end;
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:UnloadBB9090(mode, noEventSend)
	UnloadBB9090Event.sendEvent(self, mode, noEventSend);
	
		for i,v in pairs(self.bales) do
			if v.time >0.466 then
				self.TimeSet(self, i, v.time + 0.005, noEventSend);
				break;
			end;
		end;

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090.TimeSet(self, i, baleTime, noEventSend)
	TimeSetEvent.sendEvent(self, i, baleTime, noEventSend);

	if self.baleAnimCurve ~= nil then
		local bale = self.bales[i];
		if bale ~= nil then
			bale.time = baleTime;
			local v = self.baleAnimCurve:get(bale.time);
			setTranslation(bale.id, v[1], v[2], v[3]);
			setRotation(bale.id, v[4], v[5], v[6]);
			if bale.time >= 1 then
				self.DroppBale(self, i);
				self.BBCurrent = self.BBCurrent +1;
				self.BBTotal = self.BBTotal +1;
			end;
		end;
	end;

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090.DroppBale(self, baleIndex)
	local bale = self.bales[baleIndex];
	local x,y,z = getWorldTranslation(bale.id);
	local rx,ry,rz = getWorldRotation(bale.id);
	local baleObject = Bale:new(self.isServer, self.isClient);
	baleObject:load(bale.filename, x,y,z,rx,ry,rz);
	baleObject:register();
	local lx, ly, lz = bale.lastX, bale.lastY, bale.lastZ;
	setLinearVelocity(baleObject.nodeId, (x-lx)/1, (y-ly)/1, (z-lz)/1);
	delete(bale.id);
	table.remove(self.bales, baleIndex);
	self.unloadBales = false;
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:EmptyBB9090(mode, noEventSend)
	EmptyBB9090Event.sendEvent(self, mode, noEventSend);
	
	for i=1, 2 do
		local v = self.bales[i];
		if v~=nil then
			self.TimeSet(self, i, v.time + 0.005, noEventSend);
		end;
	end;
	
	if table.getn(self.bales) ==0 then
		self.emptyBaler = false;
		self.fillLevel = 0;
		self.previousLevel = 0;
	end;

end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:getIsAreaActive()
	return self.pickUpPos;
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	if not resetVehicles then
		self.BBTotal = Utils.getNoNil(getXMLInt(xmlFile, key.."#totalBales"),0);
		self.pickUpPos = Utils.getNoNil(getXMLBool(xmlFile, key.."#pickUp"),false);
		self:pickUpMode(self.pickUpPos);
		self.workPos = Utils.getNoNil(getXMLBool(xmlFile, key.."#workPos"),false);
		self:WorkBB9090(self.workPos);
		self.unloadBales = Utils.getNoNil(getXMLBool(xmlFile, key.."#unloadBales"),false);
		self.allowTransport = Utils.getNoNil(getXMLBool(xmlFile, key.."#allowTransport"),true);
		self.emptyBaler = Utils.getNoNil(getXMLBool(xmlFile, key.."#emptyBaler"),false);
	end;
	
	for i, v in pairs(self.componentJoints) do
		setJointFrame(self.componentJoints[i].jointIndex, 0, self.componentJoints[i].jointNode);
	end;
	
	return BaseMission.VEHICLE_LOAD_OK;
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:getSaveAttributesAndNodes(nodeIdent)
	local attributes = 'totalBales="'..tostring(self.BBTotal)..
	'" pickUp="'..tostring(self.pickUpPos)..
	'" workPos="'..tostring(self.workPos)..
	'" unloadBales="'..tostring(self.unloadBales)..
	'" allowTransport="'..tostring(self.allowTransport)..
	'" emptyBaler="'..tostring(self.emptyBaler)..'"';
	local nodes = nil;
	
	return attributes,nodes;
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:readStream(streamId, connection)
    self:WorkBB9090(streamReadBool(streamId), true);
    self:pickUpMode(streamReadBool(streamId), true);
	self.BBCurrent = streamReadInt32(streamId);
	self.BBTotal = streamReadInt32(streamId);
	self.emptyBaler = streamReadBool(streamId);
	self.allowTransport = streamReadBool(streamId);
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090:writeStream(streamId, connection)
    streamWriteBool(streamId, self.workPos);
    streamWriteBool(streamId, self.pickUpPos);
	streamWriteInt32(streamId, self.BBCurrent);
	streamWriteInt32(streamId, self.BBTotal);
	streamWriteBool(streamId, self.emptyBaler);
	streamWriteBool(streamId, self.allowTransport);
end;

--________________________________________________________________________________________________________________________________________________________
function BB9090.baleCounter(self, baleIndex)
	if self.BBCurrent ~= nil and self.BBTotal ~= nil then
		self.BBCurrent = self.BBCurrent +1;
		self.BBTotal = self.BBTotal +1;
	end;
end;

Baler.dropBale = Utils.appendedFunction(Baler.dropBale, BB9090.baleCounter);