--
-- MAN HKL
-- Specialization for MAN Hooklift
-- Spezialisierung für MAN Hakenlift
-- @Anpassung  VWFahrer80
-- 
-- frei verwendbar - keine erlaubnis nötig  |  free for use - no permission needed.
-- Modifikationen erst nach Rücksprache!    |  modifications only with my permission.
--
-- Hinweis: das kopieren von Sourcecode ist strafbar nach UrhG §2.1
-- edit by SirRobin 17.11.2011

MANHKL = {};

function MANHKL.prerequisitesPresent(specializations)
    Vehicle.registerJointType("HookJoint");
	print("MAN TGX Hakenlift is loaded");
	return true;
end;

function MANHKL:load(xmlFile)

	self.setRpmUp = SpecializationUtil.callSpecializationsFunction("setRpmUp");

	local hydraulicsCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.hydraulics#count"), 0);	
	self.hydraulics = {};	
	for i=1, hydraulicsCount do
		local hydraulicName = string.format("vehicle.hydraulics.hydraulic%d", i);		
		self.hydraulics[i] = {};		
		self.hydraulics[i].node = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#index"));
		self.hydraulics[i].punch = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#punch"));
		self.hydraulics[i].translationPunch = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#punchFixpoint"));
		self.hydraulics[i].fixPoint = Utils.indexToObject(self.components, getXMLString(xmlFile, hydraulicName .. "#fixpoint"));
		if self.hydraulics[i].punch ~= nil and self.hydraulics[i].translationPunch ~= nil then
			local ax, ay, az = getWorldTranslation(self.hydraulics[i].punch);
			local bx, by, bz = getWorldTranslation(self.hydraulics[i].translationPunch);		
			self.hydraulics[i].punchDistance = Utils.vector3Length(ax-bx, ay-by, az-bz);
		end;
	end;
	
	local tipAnimRootNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.tipAnimation#rootNode"));
	self.tipAnimCharSet = 0;
	if tipAnimRootNode ~= nil and tipAnimRootNode ~= 0 then
		self.tipAnimCharSet = getAnimCharacterSet(tipAnimRootNode);
		if self.tipAnimCharSet ~= 0 then
			local clip = getAnimClipIndex(self.tipAnimCharSet, getXMLString(xmlFile, "vehicle.tipAnimation#clip"));
			assignAnimTrackClip(self.tipAnimCharSet, 0, clip);
			setAnimTrackLoopState(self.tipAnimCharSet, 0, false);
			self.tipAnimSpeedScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.tipAnimation#speedScale"), 1);
			self.tipAnimDuration = getAnimClipDuration(self.tipAnimCharSet, clip);
		end;
	end;
	self.tipReferencePoint = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.tipReferencePoint#index"));
	
	self.attacherJoints[1].jointType = Vehicle.JOINTTYPE_HOOKJOINT;
	self.firstAttachOnLoad = false;
	self.firstAttachTime = 4000;
	self.attachableObject = nil;
	self.isHakenliftTrailer = true;
	self.liftAxisAutoDown = false;
	self.saveMinRpm = 0;
	
	self.objectTipAnimDuration = nil;
	self.objectTipAnimSpeedScale = nil;
	self.objectTipDischargeEndTime = nil;
	self.objectTipState = nil;
	self.objectTipReferencePoint = nil;
	self.tipState = 0;
	
end;

function MANHKL:delete()
end;

function MANHKL:readStream(streamId, connection)

end;

function MANHKL:writeStream(streamId, connection)

end;

function MANHKL:mouseEvent(posX, posY, isDown, isUp, button)

end;

function MANHKL:keyEvent(unicode, sym, modifier, isDown)

end;

function MANHKL:update(dt)
	
	if self.firstAttachTime > 0 then
		self.firstAttachTime = self.firstAttachTime-dt;
		if not self.firstAttachOnLoad then
			local attacherJoint = self.attacherJoints[1];
			if attacherJoint.jointIndex == 0 then
				for k, attachable in pairs(g_currentMission.attachables) do
					if attachable.attacherVehicle == nil and attachable.attacherJoint.jointType == attacherJoint.jointType then
						local px, py, pz = getWorldTranslation(attacherJoint.jointTransform);
                        local vx, vy, vz = getWorldTranslation(attachable.attacherJoint.node);
                        local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
                        if distance < 0.6 then
							self:attachImplement(attachable, 1);
							self.firstAttachOnLoad = true;
						end;
					end;
				end;
			end;
		end;
	end;
	
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.MANHKL_AXIS) then
			if self.animationParts[1].clipEndTime then
				self:setAnimationTime(1, self.animationParts[1].startPosition);
			elseif not self.liftAxisAutoDown then
				self:setAnimationTime(1, self.animationParts[1].animDuration);
			end;
		end;
		local isKeyEvent = false;
		if self.tipState == 0 then
			if InputBinding.isPressed(InputBinding.MANHKL_DOWN) and self:getIsActiveForInput() then
				self:setAnimationTime(2, self.animationParts[2].currentPosition+(self.animationParts[2].offSet*(dt/5)));
				isKeyEvent = true;
			elseif InputBinding.isPressed(InputBinding.MANHKL_UP) and self:getIsActiveForInput() then
				self:setAnimationTime(2, self.animationParts[2].currentPosition-(self.animationParts[2].offSet*(dt/5)));
				isKeyEvent = true;
			end;
		end;
		self:setRpmUp(dt, isKeyEvent);
	end;
	
	if self.liftAxisAutoDown then
		self:setAnimationTime(1, self.animationParts[1].startPosition);
	end;
	
	setJointFrame(self.attacherJoints[1].jointIndex, 0, self.attacherJoints[1].jointTransform);
	local jointDesc = self.attacherJoints[1];
	local jointLimit1 = (50/2000)*math.max(self.animationParts[2].currentPosition-2500, 0);
	local jointLimit2 = (130/2000)*math.max(self.animationParts[2].currentPosition-2500, 0);
	setJointRotationLimit(jointDesc.jointIndex, 0, true, Utils.degToRad(-0), Utils.degToRad(0));
	setJointRotationLimit(jointDesc.jointIndex, 1, true, Utils.degToRad(-jointLimit1), Utils.degToRad(jointLimit1));
	setJointRotationLimit(jointDesc.jointIndex, 2, true, Utils.degToRad(-jointLimit2), Utils.degToRad(jointLimit2));
	
	local mustAxisDown = false;
	for k, implements in pairs(self.attachedImplements) do
		local implement = implements.object;
		if implement.isHakenliftObject then
			if self.animationParts[2].clipStartTime then
				implement.tipReferencePoint = self.tipReferencePoint;
			else
				implement.tipReferencePoint = nil;
			end;
			self.objectTipAnimDuration = implement.tipAnimDuration;
			self.objectTipAnimSpeedScale = implement.tipAnimSpeedScale;
			self.objectTipDischargeEndTime = implement.tipDischargeEndTime;
			self.objectTipState = implement.tipState;
			self.tipState = implement.tipState;
		else
			self.objectTipAnimDuration = nil;
			self.objectTipAnimSpeedScale = nil;
			self.objectTipDischargeEndTime = nil;
			self.objectTipState = nil;
		end;
		if implement.fillLevel ~= nil then
			if implement.fillLevel > 2500 then
			mustAxisDown = true;
			end;
		end;
	end;
	self.liftAxisAutoDown = mustAxisDown;
	if self.objectTipAnimDuration ~= nil and self.objectTipAnimSpeedScale ~= nil and self.objectTipDischargeEndTime ~= nil and self.objectTipState ~= nil then
		local animDuration = self.objectTipAnimDuration;
		local speedScale = self.objectTipAnimSpeedScale;
		self.tipAnimSpeedScale = self.tipAnimDuration/(animDuration/speedScale);
		if self.objectTipState == Trailer.TIPSTATE_CLOSING then
			if self.tipAnimCharSet ~= 0 then
				if getAnimTrackTime(self.tipAnimCharSet, 0) > self.tipAnimDuration then
					setAnimTrackTime(self.tipAnimCharSet, 0, self.tipAnimDuration);
				end;
				setAnimTrackSpeedScale(self.tipAnimCharSet, 0, -self.tipAnimSpeedScale);
				enableAnimTrack(self.tipAnimCharSet, 0);
			end;
		elseif self.objectTipState == Trailer.TIPSTATE_OPENING then
			if self.tipAnimCharSet ~= 0 then
				if getAnimTrackTime(self.tipAnimCharSet, 0) < 0.0 then
					setAnimTrackTime(self.tipAnimCharSet, 0, 0.0);
				end;
				setAnimTrackSpeedScale(self.tipAnimCharSet, 0, self.tipAnimSpeedScale);
				enableAnimTrack(self.tipAnimCharSet, 0);
			end;
		elseif self.objectTipState == Trailer.TIPSTATE_CLOSED then
			disableAnimTrack(self.tipAnimCharSet, 0);
		end;
	else
		setAnimTrackTime(self.tipAnimCharSet, 0, getAnimTrackTime(self.tipAnimCharSet, 0));
		setAnimTrackSpeedScale(self.tipAnimCharSet, 0, -self.tipAnimSpeedScale);
		enableAnimTrack(self.tipAnimCharSet, 0);
		if getAnimTrackTime(self.tipAnimCharSet, 0) <= 0.0 then
			disableAnimTrack(self.tipAnimCharSet, 0);
		end;
	end;
end;

function MANHKL:updateTick(dt)

	for i=1, table.getn(self.hydraulics) do
		local ax, ay, az = getWorldTranslation(self.hydraulics[i].node);
		local bx, by, bz = getWorldTranslation(self.hydraulics[i].fixPoint);
		if bx ~= nil and by ~= nil and bz ~= nil then
			local x, y, z = worldDirectionToLocal(getParent(self.hydraulics[i].node), bx-ax, by-ay, bz-az);
			setDirection(self.hydraulics[i].node, x, y, z, 0, 0, 1);
			local distance = Utils.vector3Length(ax-bx, ay-by, az-bz);
			if self.hydraulics[i].punch ~= nil and self.hydraulics[i].punchDistance ~= nil and self.hydraulics[i].translationPunch then
				if self.hydraulics[i].doScale then
					local xScale, yScale, zScale = getScale(self.hydraulics[i].punch);
					local newScale = xScale * (distance / self.hydraulics[i].punchDistance);
					setScale(self.hydraulics[i].punch, 1, 1, newScale);
				else
					setTranslation(self.hydraulics[i].punch, 0, 0, distance-self.hydraulics[i].punchDistance);
				end;
			end;
		end;
	end;
end;

function MANHKL:setRpmUp(dt, isActive)
		if dt ~= nil then
			if isActive == true then
				self.motor.minRpm = math.max(self.motor.minRpm-dt, -1000);
			else
				self.motor.minRpm = math.min(self.motor.minRpm+dt*2, self.saveMinRpm);
			end;
		else
			self.motor.minRpm = self.saveMinRpm;
		end;
		if self.isMotorStarted then
			local fuelUsed = 0.0000011*math.abs(self.motor.minRpm);
			self:setFuelFillLevel(self.fuelFillLevel-fuelUsed);
			g_currentMission.missionStats.fuelUsageTotal = g_currentMission.missionStats.fuelUsageTotal + fuelUsed;
			g_currentMission.missionStats.fuelUsageSession = g_currentMission.missionStats.fuelUsageSession + fuelUsed;
		end;
end;

function MANHKL:draw()
	g_currentMission:addExtraPrintText(string.format(""..InputBinding.getKeyNamesOfDigitalAction(InputBinding.MANHKL_UP) .. " / " .. InputBinding.getKeyNamesOfDigitalAction(InputBinding.MANHKL_DOWN)..":            "..g_i18n:getText("MANHKL_3")..""));
	if self.animationParts[1].clipEndTime then
		g_currentMission:addHelpButtonText(g_i18n:getText("MANHKL_4"), InputBinding.MANHKL_AXIS);
	elseif not self.liftAxisAutoDown then
		g_currentMission:addHelpButtonText(g_i18n:getText("MANHKL_5"), InputBinding.MANHKL_AXIS);
	end;
end;