--
-- AloeFrontloader
-- Specialization for all Alö frontloaders
--
-- @author  Stefan Maurus	
-- @date  06/03/12

-- Copyright © Stefan Maurus, www.stefanmaurus.de

-- setVehicleIncreaseRpm by fruktor

Vehicle.registerJointType("aloeFrontloader");

AloeFrontloader = {};

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

function AloeFrontloader:load(xmlFile)	
	--armPipes
    self.mesh = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.armPipes#mesh"));
	setVisibility(self.mesh, false);	
	
    self.deattachedPipes = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.armPipes#deAttachedPipes"));
	setVisibility(self.deattachedPipes, true);	
	
	self.animFactor = 0;
	
	self.animatedArmPipesAnimation = {};
    self.animatedArmPipesAnimation.animCharSet = 0;
  
    local rootNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.armPipes#rootNode"));
  
    if rootNode ~= nil then
        self.animatedArmPipesAnimation.animCharSet = getAnimCharacterSet(rootNode);
        if self.animatedArmPipesAnimation.animCharSet ~= 0 then
            self.animatedArmPipesAnimation.clip = getAnimClipIndex(self.animatedArmPipesAnimation.animCharSet, getXMLString(xmlFile, "vehicle.aloeFrontloader.armPipes#clip"));
            if self.animatedArmPipesAnimation.clip >= 0 then
                assignAnimTrackClip(self.animatedArmPipesAnimation.animCharSet, 0, self.animatedArmPipesAnimation.clip);
                setAnimTrackSpeedScale(self.animatedArmPipesAnimation.animCharSet, self.animatedArmPipesAnimation.clip, 0);
                setAnimTrackLoopState(self.animatedArmPipesAnimation.animCharSet, 0, false);
            end;
        end;
    end;	
	
	--toolPipes
    self.mesh1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.toolPipes#mesh1"));
    self.mesh2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.toolPipes#mesh2"));
    self.mesh3 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.toolPipes#mesh3"));
	
	self.animatedToolPipesAnimation = {};
    self.animatedToolPipesAnimation.animCharSet = 0;

    local rootNode1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.toolPipes#rootNode"));
  
    if rootNode1 ~= nil then
        self.animatedToolPipesAnimation.animCharSet = getAnimCharacterSet(rootNode1);
        if self.animatedToolPipesAnimation.animCharSet ~= 0 then
            self.animatedToolPipesAnimation.clip = getAnimClipIndex(self.animatedToolPipesAnimation.animCharSet, getXMLString(xmlFile, "vehicle.aloeFrontloader.toolPipes#clip"));
            if self.animatedToolPipesAnimation.clip >= 0 then
                assignAnimTrackClip(self.animatedToolPipesAnimation.animCharSet, 0, self.animatedToolPipesAnimation.clip);
                setAnimTrackSpeedScale(self.animatedToolPipesAnimation.animCharSet, self.animatedToolPipesAnimation.clip, 0);
                setAnimTrackLoopState(self.animatedToolPipesAnimation.animCharSet, 0, false);
            end;
        end;
    end;
	
	link(getRootNode(),self.mesh);	
	link(getRootNode(),self.mesh1);
	link(getRootNode(),self.mesh2);
	link(getRootNode(),self.mesh3);	
	
	--lcs
	self.LCSVis = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.aloeFrontloader.loaderControlSystem#index"));	
	setVisibility(self.LCSVis, false)
	--lock
	self.aloeToolAttachAnim = getXMLString(xmlFile, "vehicle.aloeFrontloader.attach#animation");
	
	--HUD
	self.aloe_hud = Overlay:new("aloe_hud", Utils.getFilename("Trima/aloe_hud.dds", self.baseDirectory), 0.405, 0.01238, 0.2371, 0.039525);
	self.aloeArmFalse_hud = Overlay:new("aloeArmFalse_hud", Utils.getFilename("Trima/aloeArmFalse_hud.dds", self.baseDirectory), 0.405, 0.01238, 0.2371, 0.039525);
	self.aloeArmTrue_hud = Overlay:new("aloeArmTrue_hud", Utils.getFilename("Trima/aloeArmTrue_hud.dds", self.baseDirectory), 0.405, 0.01238, 0.2371, 0.039525);
	self.aloeToolFalse_hud = Overlay:new("aloeToolFalse_hud", Utils.getFilename("Trima/aloeToolFalse_hud.dds", self.baseDirectory), 0.405, 0.01238, 0.2371, 0.039525);
	self.aloeToolTrue_hud = Overlay:new("aloeToolTrue_hud", Utils.getFilename("Trima/aloeToolTrue_hud.dds", self.baseDirectory), 0.405, 0.01238, 0.2371, 0.039525);
	
	self.ToolIsAttached= false;
	self.AttachTimer = 0;	
	self.ShowMouse = false;	
	self.attachedTool = nil;
--	self.toolHasMovingTools = false;
	
    self.setVehicleIncreaseRpm = SpecializationUtil.callSpecializationsFunction("setVehicleIncreaseRpm");
    self.saveMinimumRpm = 0;	
	self.lastRotSpeed3 = 0;
	self.lastRotSpeed4 = 0;	
	
--	self.attacherPlateRotMin1 = getXMLFloat(xmlFile, "vehicle.aloeFrontloader.attacherPlate#rotMin1")
--	self.attacherPlateRotMin2 = getXMLFloat(xmlFile, "vehicle.aloeFrontloader.attacherPlate#rotMin2")
	
	self.limitArmMin = math.rad(getXMLFloat(xmlFile, "vehicle.aloeFrontloader.deAttach#limitArmMin"));
	self.limitArmMax = math.rad(getXMLFloat(xmlFile, "vehicle.aloeFrontloader.deAttach#limitArmMax"));	
	self.limitToolMin = math.rad(getXMLFloat(xmlFile, "vehicle.aloeFrontloader.deAttach#limitToolMin"));
	self.limitToolMax = math.rad(getXMLFloat(xmlFile, "vehicle.aloeFrontloader.deAttach#limitToolMax"));	
	self.animationWithoutTool = getXMLString(xmlFile, "vehicle.aloeFrontloader.deAttach#animationWithoutTool");
	self.animationWithTool = getXMLString(xmlFile, "vehicle.aloeFrontloader.deAttach#animationWithTool");

	self.printWarningTime = 0;
end;

function AloeFrontloader:delete()
    delete(self.mesh);
    delete(self.mesh1);
    delete(self.mesh2);
    delete(self.mesh3);	
end;

function AloeFrontloader:readStream(streamId, connection)
end;

function AloeFrontloader:writeStream(streamId, connection) 
end;

function AloeFrontloader:detachImplement()
	self.ToolIsAttached = false;
	self.attachedTool = nil;
end;

function AloeFrontloader:attachImplement(implement)
	self.ToolIsAttached = true;			
	self.attachedTool = implement.object;
--	if implement.object.movingTools == nil then
--		self.toolHasMovingTools = false;
--	else
---		self.toolHasMovingTools = true;	
--	end;
end;

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

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

function AloeFrontloader:update(dt)	
	--deattach	
	if self:getIsActiveForInput() then
		if not self.allowsDetaching then
			if InputBinding.hasEvent(InputBinding.ATTACH) and g_currentMission.attachableInMountRange == nil then
				self.printWarningTime = self.time + 10000;
			end;
		end;
	end;	
	
	--[[rotationregulation
	
	local factor = math.abs((xGrad/minMax)-1);
	if factor > 0.5 then
		self.movingTools[2].rotMin = math.rad(self.attacherPlateRotMin1);	
	elseif factor < 0.5 then	
		local rotMinNew = ((factor*2)*(self.attacherPlateRotMin1-self.attacherPlateRotMin2))+self.attacherPlateRotMin2;
		self.movingTools[2].rotMin = math.rad(rotMinNew);
	end;]]
	
	local x, _, _ = getRotation(self.movingTools[1].node);
	local xGrad = math.abs(math.deg(x)-math.deg(self.movingTools[1].rotMax));
	local minMax = math.abs(math.deg(self.movingTools[1].rotMin)-math.deg(self.movingTools[1].rotMax));		
	
	--pipes
	if self:getIsActive() then	
		self.animFactor = xGrad/minMax;		
		--enableAnimTrack(self.animatedArmPipesAnimation.animCharSet, 0);--
		--local duration = getAnimClipDuration(self.animatedArmPipesAnimation.animCharSet, self.animatedArmPipesAnimation.clip)--
		if self.animFactor < 0 then
			self.animFactor = 0;
		elseif self.animFactor > 0.999 then
			self.animFactor = 0.999;
		end;
		--setAnimTrackTime(self.animatedArmPipesAnimation.animCharSet, 0, duration*self.animFactor, true);--
		enableAnimTrack(self.animatedToolPipesAnimation.animCharSet, 0);
		local duration1 = getAnimClipDuration(self.animatedToolPipesAnimation.animCharSet, self.animatedToolPipesAnimation.clip)
		setAnimTrackTime(self.animatedToolPipesAnimation.animCharSet, 0, duration1*self.animFactor, true);	
	else
		--disableAnimTrack(self.animatedArmPipesAnimation.animCharSet, 0);--	
		disableAnimTrack(self.animatedToolPipesAnimation.animCharSet, 0);	
	end;

	
	--lockanimation	
	if self.ToolIsAttached then
		self:playAnimation(self.aloeToolAttachAnim, 1, self:getAnimationTime( self.aloeToolAttachAnim), true);					
	else
		self:playAnimation(self.aloeToolAttachAnim, -1, self:getAnimationTime( self.aloeToolAttachAnim), true);		
	end;
	
	--rpm
	if self.attacherVehicle ~= nil then
		if self.attacherVehicle.motor ~= nil then	
			local lastRotSpeed1 = math.abs(self.movingTools[1].lastRotSpeed);	
			local lastRotSpeed2 = math.abs(self.movingTools[2].lastRotSpeed);
			self.lastRotSpeed3 = 0;
			self.lastRotSpeed4 = 0;		
		--	if self.attachedTool ~= nil then
		--		if self.toolHasMovingTools then
		--			if self.attachedTool.movingTools[1].rotMax ~= nil then
		--				self.lastRotSpeed3 = math.abs(self.attachedTool.movingTools[1].lastRotSpeed);		
		--			elseif self.attachedTool.movingTools[1].transMax ~= nil then
		---				self.lastRotSpeed4 = math.abs(self.attachedTool.movingTools[1].lastTransSpeed);			
		--			end;
		--		end;
		--	end;
			self:setVehicleIncreaseRpm(dt, 30*((lastRotSpeed1+lastRotSpeed2+self.lastRotSpeed3+self.lastRotSpeed4)*10000), true);	
		end;
	end;
end;

function AloeFrontloader:updateTick(dt)
	if self:getIsActive() then
		local x,_,_ = getRotation(self.movingTools[1].node);
		local x1,_,_ = getRotation(self.movingTools[2].node);		
		self.allowsDetaching = x > self.limitArmMin and x < self.limitArmMax and x1 > self.limitToolMin and x1 < self.limitToolMax;		
		self.allowsDetachingArm = x > self.limitArmMin and x < self.limitArmMax;		
		self.allowsDetachingTool = x1 > self.limitToolMin and x1 < self.limitToolMax;		
	end;
end;

function AloeFrontloader:onAttach(attacherVehicle)
	if self.attacherVehicle ~= nil then
		if self.attacherVehicle.LCSNode ~= nil then
			link(self.attacherVehicle.LCSNode, self.LCSVis)
			setVisibility(self.LCSVis, true)		
		end;
	end;
	setVisibility(self.deattachedPipes, false);		
	setVisibility(self.mesh, true);	
	
	self.attacherVehicle = attacherVehicle;
	if self.attacherVehicleCopy1 == nil then
		self.attacherVehicleCopy1 = self.attacherVehicle;
	end;
	if self.attacherVehicle.motor ~= nil then
		self.saveMinimumRpm = self.attacherVehicle.motor.minRpm;
	else
		if self.attacherVehicle.saveMinRpm ~= nil then
			self.saveMinimumRpm = self.attacherVehicle.saveMinimumRpm;
		else
			self.attacherVehicle.saveMinimumRpm  = 100;
		end;
	end;
	
	if self.ToolIsAttached then
		self:playAnimation(self.animationWithTool, -1, self:getAnimationTime(self.animationWithTool), true);	
	else
		self:playAnimation(self.animationWithoutTool, -1, self:getAnimationTime(self.animationWithoutTool), true);			
	end;
end;

function AloeFrontloader:onDetach()
	for k, steerable in pairs(g_currentMission.steerables) do
		if self.attacherVehicleCopy1 == steerable then
			steerable.motor.minRpm = self.saveMinimumRpm;
			self.attacherVehicleCopy1 = nil;
		end;
	end;

	unlink(self.LCSVis)
	setVisibility(self.LCSVis, false)	
	setVisibility(self.deattachedPipes, true);		
	setVisibility(self.mesh, false);
	if self.ToolIsAttached then
		self:playAnimation(self.animationWithTool, 1, self:getAnimationTime(self.animationWithTool), true);	
	else
		self:playAnimation(self.animationWithoutTool, 1, self:getAnimationTime(self.animationWithoutTool), true);			
	end;	
end;

function AloeFrontloader:draw()
	if self.printWarningTime > self.time and g_currentMission.attachableInMountRange == nil then
		g_currentMission:addWarning(g_i18n:getText("ALOE_FRONTLOADER_DEATTACH_WARNING"));
	else
		self.printWarningTime = self.time;
	end;
	
	self.aloe_hud:render();
	setTextBold(true);
	renderText(0.4352, 0.028, 0.01, string.format("%s    %s", g_i18n:getText("ALOE_ARM"), g_i18n:getText("ALOE_TOOL")));
	setTextBold(false);
	if self.allowsDetachingArm then
		self.aloeArmTrue_hud:render();
	else
		self.aloeArmFalse_hud:render();	
	end;
	if self.allowsDetachingTool then
		self.aloeToolTrue_hud:render();
	else
		self.aloeToolFalse_hud:render();	
	end;	
end

function AloeFrontloader:setVehicleIncreaseRpm(dt, increase, isActive)
	if self.attacherVehicle ~= nil and self.saveMinimumRpm ~= 0 and
		self.attacherVehicle.motor ~= nil then
		if dt ~= nil then
			if isActive == true then
				self.attacherVehicle.motor.minRpm = math.max(self.attacherVehicle.motor.minRpm-(dt*2), -increase);
			else
				self.attacherVehicle.motor.minRpm = math.min(self.attacherVehicle.motor.minRpm+(dt*5), self.saveMinimumRpm);
			end;
		else
			self.attacherVehicle.motor.minRpm = self.saveMinimumRpm;
		end;
		if self.attacherVehicle.isMotorStarted then
			local fuelUsed = 0.0000012*math.abs(self.attacherVehicle.motor.minRpm);
			self.attacherVehicle:setFuelFillLevel(self.attacherVehicle.fuelFillLevel-fuelUsed);
			g_currentMission.missionStats.fuelUsageTotal = g_currentMission.missionStats.fuelUsageTotal + fuelUsed;
			g_currentMission.missionStats.fuelUsageSession = g_currentMission.missionStats.fuelUsageSession + fuelUsed;
		end;
	end;
end;