--
--
-- @inspired by: 	- forage wagon, by Heady [www.planet-ls.de]
--					- forage wagon, by GIANTS 
--				
-- @version 		v1.1
-- @date  			26/12/10
-- @author  		fruktor
--

BergmannShuttle700s = {};




function BergmannShuttle700s.prerequisitesPresent(specializations)
	return true;
end;

function BergmannShuttle700s:load(xmlFile)

	self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
	self.setCollectPSActive = SpecializationUtil.callSpecializationsFunction("setCollectPSActive");

	self.rollsDis = {};
	self.rollsDis.object = {};
	self.rollsDis.speed = {};
	local i=1;
	while true do 
		local tmp = Utils.indexToObject(self.components, getXMLString(xmlFile, string.format("vehicle.bergmann#rollDis%d",i)));
		if tmp == nil then
			break;
		end;
		self.rollsDis.object[i] = tmp;
		self.rollsDis.speed[i] = 0;
		i=i+1;
	end;
	
    local forageWgnSound = getXMLString(xmlFile, "vehicle.forageWgnSound#file");
    if forageWgnSound ~= nil and forageWgnSound ~= "" then
        forageWgnSound = Utils.getFilename(forageWgnSound, self.baseDirectory);
        self.forageWgnSound = createSample("forageWgnSound");
        self.forageWgnSoundEnabled = false;
        loadSample(self.forageWgnSound, forageWgnSound, false);
        self.forageWgnSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.forageWgnSound#pitchOffset"), 1);
        self.forageWgnSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.forageWgnSound#volume"), 1.0);
    end;
	
	local rollsCount = getXMLInt(xmlFile, "vehicle.rolls#count");
	self.rolls = {}
	if rollsCount ~= nil then		
		for i=1, rollsCount do
			local entry = {};
			local rollPartname = string.format("vehicle.rolls.roll" .. "%d", i);
			entry.index = Utils.indexToObject(self.components, getXMLString(xmlFile, rollPartname .. "#index"));
			entry.speedScale = Utils.getNoNil(getXMLInt(xmlFile, rollPartname .. "#speedScale"), 1)/1000;
			table.insert(self.rolls, entry);
		end;
	end;

    self.fillScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillScale#value"), 1);

    self.isTurnedOn = false;	
	self.speedViolationMaxTime = 3000;
	self.speedViolationTimer = self.speedViolationMaxTime;
	
	local psPath = string.format("vehicle.bergmann.collectPS");
	local collectPS = {};
	local particleNode = Utils.loadParticleSystem(xmlFile, collectPS, psPath, self.components, false, "$data/vehicles/particleSystems/trailerDischargeParticleSystem.i3d", self.baseDirectory);
	self.collectPS = collectPS;
	self.activateCollectPS = false;

	local psDryPath = string.format("vehicle.bergmann.collectPSdry");
	local collectPSdry = {};
	local particleNode = Utils.loadParticleSystem(xmlFile, collectPSdry, psDryPath, self.components, false, "$data/vehicles/particleSystems/trailerDischargeParticleSystem.i3d", self.baseDirectory);
	self.collectPSdry = collectPSdry;
	
end;

function BergmannShuttle700s:delete()
    if self.forageWgnSound ~= nil then
        delete(self.forageWgnSound);
    end;
end;

function BergmannShuttle700s:readStream(streamId, connection)
	self.isTurnedOn = streamReadBool(streamId);
	self.activateCollectPS = streamReadBool(streamId);
end;

function BergmannShuttle700s:writeStream(streamId, connection)
	streamWriteBool(streamId, self.isTurnedOn);
	streamWriteBool(streamId, self.activateCollectPS);
end;

function BergmannShuttle700s:mouseEvent(posX, posY, isDown, isUp, button)
end;

function BergmannShuttle700s:keyEvent(unicode, sym, modifier, isDown)
end;

function BergmannShuttle700s:update(dt)
    if self:getIsActiveForInput() then
        if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) then
			self:setIsTurnedOn(not self.isTurnedOn);
        end;
	end;
end;


function BergmannShuttle700s:updateTick(dt)	

	if self.varTip ~= nil then
		if self.varTip.trailerCount > 1 then
			if self.varTip.activeTrailerIdx ~= self.varTip.trailerNr then
				return;
			end;
		end;
	end;

	-- ####
	if self.doJointSearchCylindered then
		for k,v in pairs(self.attacherVehicle.attachedImplements) do
			if v.object == self then
				local joint = self.attacherVehicle.attacherJoints[v.jointDescIndex];
				self.vehicleJoint = joint;
				self.doJointSearchCylindered = false;
				break;
			end;
		end;
		self.doJointSearchCylindered = false;
	end;
	
	-- #### update the attacherJoint!     
    if self.vehicleJoint ~= nil then
        setJointFrame(self.vehicleJoint.jointIndex, 1, self.attacherJoint.node);
	end;
	
	-- ### update PowerShaft!
	if self.attacherVehiclePowerShaft ~= nil then
		self.doJointSearch = true;
	end;
		

	-- #### entladewalzen
	if	self.tipState == Trailer.TIPSTATE_OPEN then
		for i, j in pairs(self.rollsDis.object) do
			local rX, rY, rZ = getRotation(j);
			self.rollsDis.speed[i] = self.rollsDis.speed[i] + 0.005 + math.random()/200;
			self.rollsDis.speed[i] = math.min(self.rollsDis.speed[i], 0.4);
			if i==2 then
				rX = rX - self.rollsDis.speed[i];
			else
				rX = rX + self.rollsDis.speed[i];
			end;
			setRotation(j, rX, rY, rZ);
		end;
	end;
	if self.tipState == Trailer.TIPSTATE_CLOSING then
		for i, j in pairs(self.rollsDis.object) do
			local rX, rY, rZ = getRotation(j);
			self.rollsDis.speed[i] = self.rollsDis.speed[i] - 0.005 - math.random()/200;
			self.rollsDis.speed[i] = math.max(self.rollsDis.speed[i], 0.0);
			if i==2 then
				rX = rX + self.rollsDis.speed[i];
			else
				rX = rX - self.rollsDis.speed[i];
			end;
			setRotation(j, rX, rY, rZ);
		end;
	end;

	-- ### speed control
	self.wasToFast = false;
	if self.isTurnedOn and self.pickup.isDown then
		local speedLimit = 20;
		if self.maxSpeedLevel == 2 then
			speedLimit = 30;
		elseif self.maxSpeedLevel == 3 then
			speedLimit = 100;
		end;
		if self:doCheckSpeedLimit() and self.lastSpeed*3600 > speedLimit then
			self.speedViolationTimer = self.speedViolationTimer - dt;
			if self.isServer then
				if self.speedViolationTimer < 0 then
					if self.attacherVehicle ~= nil then
						--self.attacherVehicle:detachImplementByObject(self);
						self.wasToFast = true;
					end;
				end;
		   end;
		else
		   self.speedViolationTimer = self.speedViolationMaxTime;
	   end;
	end;
	
	-- #### forage wagon  ...
	
    if self:getIsActive() then	
	
		local activateCollectPS = false;	
	
		if self.fillLevel >= self.capacity then
			self.isTurnedOn = false;
		end;
		
        if self.isTurnedOn and self.wasToFast == false then

            if self.isServer and self.pickup.isDown and self.capacity > self.fillLevel then
				local cuttingAreasSend = {};
				for k, cuttingArea in pairs(self.cuttingAreas) do
					if self:getIsAreaActive(cuttingArea) then
						local x,y,z = getWorldTranslation(cuttingArea.start);
						local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
						local x2,y2,z2 = getWorldTranslation(cuttingArea.height);

						table.insert(cuttingAreasSend, {x,z,x1,z1,x2,z2});
					end;
				end;
				if (table.getn(cuttingAreasSend) > 0) then				
					local area = 0;
					local fruitType = FruitUtil.FRUITTYPE_UNKNOWN;
					for fillType,v in pairs(self.fillTypes) do						
						if fillType ~= FruitUtil.FRUITTYPE_UNKNOWN then							
							if self.currentFillType == fillType or self.currentFillType == FruitUtil.FRUITTYPE_UNKNOWN then	
								fruitType = FruitUtil.fillTypeToFruitType[fillType];
								area = BergmannAreaEvent.runLocally(cuttingAreasSend, fruitType);

								if area > 0 then
									self.currentFillType = fillType;
								end;
							end;
						end;
					end;
				
					if area > 0 then
						local pixelToSqm = g_currentMission:getFruitPixelsToSqm(); -- 4096px are mapped to 2048m
						local literPerSqm = g_strawLitersPerSqm * 2;
						local sqm = area*pixelToSqm;

						local deltaLevel = sqm*literPerSqm * self.fillScale;
						if fruitType == FruitUtil.FRUITTYPE_WHEAT or fruitType == FruitUtil.FRUITTYPE_BARLEY then
							deltaLevel = deltaLevel/2;
						end;

						self:setFillLevel(self.fillLevel+deltaLevel, self.currentFillType);
						g_server:broadcastEvent(BergmannAreaEvent:new(cuttingAreasSend, fruitType));
						activateCollectPS = true;
					end;

					
				end;
            end;
			
            if self.isClient then
                if not self.forageWgnSoundEnabled and self:getIsActiveForSound() then
                    playSample(self.forageWgnSound, 0, self.forageWgnSoundVolume, 0);
                    setSamplePitch(self.forageWgnSound, self.forageWgnSoundPitchOffset);
                    self.forageWgnSoundEnabled = true;
                end;
            end;
        end;

		
		
		if self.rolls ~= nil then		
			if self.pickup.isDown then
				rotate(self.rolls[1].index, dt*self.rolls[1].speedScale*self.attacherVehicle.lastSpeed*3600, 0, 0);
				rotate(self.rolls[2].index, dt*self.rolls[2].speedScale*self.attacherVehicle.lastSpeed*3600, 0, 0);
			end;
		end;

		if self.isClient then
            if self.forageWgnSoundEnabled and not self.isTurnedOn then
                stopSample(self.forageWgnSound);
                self.forageWgnSoundEnabled = false;
            end;
        end;
		
		if self.isServer then
			if self.activateCollectPS ~= activateCollectPS then
				self:setCollectPSActive(activateCollectPS);
			end;
		end;			
		
    end;		
	

end;

function BergmannShuttle700s:draw()	
    if self.isTurnedOn then
		g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_off_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
	else
		g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
    end;

	if self.isTurnedOn then
		if math.abs(self.speedViolationTimer - self.speedViolationMaxTime) > 2 then
			local buttonName = InputBinding.SPEED_LEVEL1;
			if self.maxSpeedLevel == 2 then
				buttonName = InputBinding.SPEED_LEVEL2;
			elseif self.maxSpeedLevel == 3 then
				buttonName = InputBinding.SPEED_LEVEL3;
			end;
			g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast") .. "\n" .. string.format(g_i18n:getText("Cruise_control_levelN"), tostring(self.maxSpeedLevel), InputBinding.getKeyNamesOfDigitalAction(buttonName)), 0.07+0.022, 0.019+0.029);
		end;
	end;
end;

function BergmannShuttle700s:onAttach(attacherVehicle)
	self.doJointSearch = true;
	self.doJointSearchCylindered = true;
end;

function BergmannShuttle700s:onDetach()
	self.vehicleJoint = nil;
	self.doJointSearch = false;
	self.doJointSearchCylindered = false;
	
	BergmannShuttle700s.onDeactivate(self);
end;

function BergmannShuttle700s:onLeave()
    if self.deactivateOnLeave then
        BergmannShuttle700s.onDeactivate(self);
    else
        BergmannShuttle700s.onDeactivateSounds(self);
    end;
end;

function BergmannShuttle700s:onDeactivate()
    self.isTurnedOn = false;
	self:setCollectPSActive(false);
    BergmannShuttle700s.onDeactivateSounds(self);
end;


function BergmannShuttle700s:onDeactivateSounds()
    if self.forageWgnSoundEnabled then
        stopSample(self.forageWgnSound);
        self.forageWgnSoundEnabled = false;
    end;
end;

function BergmannShuttle700s:onStartTip(currentTipTrigger, noEventSend)
end;

function BergmannShuttle700s:onEndTip(noEventSend)

end;

function BergmannShuttle700s:setIsTurnedOn(turnedOn, noEventSend)
	SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
	self.isTurnedOn = turnedOn;
end;

function BergmannShuttle700s:setCollectPSActive(activatePS, noEventSend)
	SetPSActiveEvent.sendEvent(self, activatePS, false);
	self.activateCollectPS = activatePS;
	
	if self.activateCollectPS == true then
		if self.currentFillType == Fillable.FILLTYPE_GRASS then
			Utils.setEmittingState(self.collectPS, true);
			Utils.setEmittingState(self.collectPSdry, false);
		elseif self.currentFillType == Fillable.FILLTYPE_DRYGRASS then
			Utils.setEmittingState(self.collectPS, false);
			Utils.setEmittingState(self.collectPSdry, true);
		else
			Utils.setEmittingState(self.collectPS, false);
			Utils.setEmittingState(self.collectPSdry, false);			
		end;
	else
		Utils.setEmittingState(self.collectPS, false);
		Utils.setEmittingState(self.collectPSdry, false);	
	end;	
			
end;
