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

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

-- @update for fs15 2014-12-06

Vehicle.registerJointType("aloeFrontloader");

AloeFrontloader = {};

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

function AloeFrontloader:load(xmlFile)	
	self.currentAnimTime = 0;
	
	--armPipes
	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.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;
	
	--lock
	self.aloeToolAttachAnim = getXMLString(xmlFile, "vehicle.aloeFrontloader.attach#animation");
	
	--HUD
	local w, yPos = getNormalizedScreenValues(333, 184);
	local w2, h2 = getNormalizedScreenValues(0,50);
	local xPos = 1-w;
	
	if getfenv(0)["modSoilMod2"]~=nil then
		w, yPos = getNormalizedScreenValues(333, 50*0.6);
		xPos = 1-w-w;
	end;

	self.backgroundHUD = Overlay:new("background", Utils.getFilename("sources/HUD/black.dds", self.baseDirectory), xPos, yPos, w, h2);
	
	self.leftGreenHUD = Overlay:new("leftGreen", Utils.getFilename("sources/HUD/white.dds", self.baseDirectory), xPos, yPos, w*0.5, h2*0.6);
	setOverlayColor(self.leftGreenHUD.overlayId, 0, 1, 0, 1);	
	
	self.leftRedHUD = Overlay:new("leftRedHUD", Utils.getFilename("sources/HUD/white.dds", self.baseDirectory), xPos, yPos, w*0.5, h2*0.6);
	setOverlayColor(self.leftRedHUD.overlayId, 1, 0, 0, 1);
	
	self.rightGreenHUD = Overlay:new("rightGreenHUD", Utils.getFilename("sources/HUD/white.dds", self.baseDirectory), xPos+(w*0.5), yPos, w*0.5, h2*0.6);
	setOverlayColor(self.rightGreenHUD.overlayId, 0, 1, 0, 1);	
	
	self.rightRedHUD = Overlay:new("rightRedHUD", Utils.getFilename("sources/HUD/white.dds", self.baseDirectory), xPos+(w*0.5), yPos, w*0.5, h2*0.6);
	setOverlayColor(self.rightRedHUD.overlayId, 1, 0, 0, 1);
	
	local _, high = getNormalizedScreenValues(0, 15);
	local _, border = getNormalizedScreenValues(0, 5);
	local _, high2 = getNormalizedScreenValues(0, 10);
			
	self.textPositionX = xPos;
	self.textPositionY = yPos+(border*2);
	self.text2PositionY = yPos+(h2*0.6)+border;
	self.text2High = high2;
	self.textHigh = high;
	self.textWidth = w-(border*2);
	self.hudWidth = w;
	self.hudIsVisable = true;
	
	--detach
	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.detachedCenterOfMass = {Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.components.component1#centerOfMass"))};
	self.attachedCenterOfMass = {Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.aloeFrontloader.attach#centerOfMass"))};
	
	--general
	self.implementIsAttached = false;
	self.updateMovingPartsOnce = false;
	
	self.afterDetachTimer = 0;
	
	self.frontloaderID = 0;
	for i = 1, table.getn(g_currentMission.vehicles) do
		if SpecializationUtil.hasSpecialization(AloeFrontloader,  g_currentMission.vehicles[i].specializations) then
			self.frontloaderID = g_currentMission.vehicles[i].frontloaderID + 1;
		end;
	end;	
end;

function AloeFrontloader:delete()
end;

function AloeFrontloader:readStream(streamId, connection)
end;

function AloeFrontloader:writeStream(streamId, connection) 
end;

function AloeFrontloader:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	self.frontloaderID = Utils.getNoNil(getXMLFloat(xmlFile, key.."#frontloaderID"), self.frontloaderID);

	return BaseMission.VEHICLE_LOAD_OK;
end;

function AloeFrontloader:getSaveAttributesAndNodes(nodeIdent)
	local attributes = 'frontloaderID="'..self.frontloaderID..'"';
	return attributes, nil;
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 and self.afterDetachTimer == 0 then
				g_currentMission:showBlinkingWarning(g_i18n:getText("ALOE_FRONTLOADER_DEATTACH_WARNING"), 6500);
			end;
		end;
		
		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA4) then
			self.hudIsVisable = not self.hudIsVisable;
		end;
	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.currentAnimTime = math.max(math.min(math.abs(1-(xGrad/minMax)), 0.999), 0);		
		enableAnimTrack(self.animatedArmPipesAnimation.animCharSet, 0);
		local duration = getAnimClipDuration(self.animatedArmPipesAnimation.animCharSet, self.animatedArmPipesAnimation.clip)
		setAnimTrackTime(self.animatedArmPipesAnimation.animCharSet, 0, duration*self.currentAnimTime, true);	
		
		enableAnimTrack(self.animatedToolPipesAnimation.animCharSet, 0);
		local duration1 = getAnimClipDuration(self.animatedToolPipesAnimation.animCharSet, self.animatedToolPipesAnimation.clip)
		setAnimTrackTime(self.animatedToolPipesAnimation.animCharSet, 0, duration1*self.currentAnimTime, true);	
	else
		disableAnimTrack(self.animatedArmPipesAnimation.animCharSet, 0);	
		disableAnimTrack(self.animatedToolPipesAnimation.animCharSet, 0);	
	end;

	--lockanimation	
	if table.getn(self.attachedImplements) > 0 then
		self:playAnimation(self.aloeToolAttachAnim, 1, self:getAnimationTime( self.aloeToolAttachAnim), true);					
	else
		self:playAnimation(self.aloeToolAttachAnim, -1, self:getAnimationTime( self.aloeToolAttachAnim), true);		
	end;
end;

function AloeFrontloader:updateTick(dt)
	if self.afterDetachTimer > 0 then
		self.afterDetachTimer = math.max(self.afterDetachTimer - dt, 0);
	end;

	if not self.updateMovingPartsOnce then
		for i, part in ipairs(self.movingParts) do
			Cylindered.updateMovingPart(self, part, true);
		end;
		self.updateMovingPartsOnce = true;
	end;
	
	--get allows detach
	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 table.getn(self.attachedImplements) > 0 then
		self:playAnimation(self.animationWithTool, -1, self:getAnimationTime(self.animationWithTool), true);	
	else
		self:playAnimation(self.animationWithoutTool, -1, self:getAnimationTime(self.animationWithoutTool), true);			
	end;
	
	if self.isServer then
		setCenterOfMass(self.components[1].node, unpack(self.attachedCenterOfMass));
		self.components[1].centerOfMass = { unpack(self.attachedCenterOfMass) };
	end;	
end;

function AloeFrontloader:onDetach()
	if table.getn(self.attachedImplements) > 0 then
		self:playAnimation(self.animationWithTool, 1, self:getAnimationTime(self.animationWithTool), true);	
	else
		self:playAnimation(self.animationWithoutTool, 1, self:getAnimationTime(self.animationWithoutTool), true);			
	end;
	if self.isServer then
		setCenterOfMass(self.components[1].node, unpack(self.detachedCenterOfMass));
		self.components[1].centerOfMass = { unpack(self.detachedCenterOfMass) };
	end;	
end;

function AloeFrontloader:draw()
	if self.hudIsVisable then
		self.backgroundHUD:render();
		
		setTextBold(false);
		
		setTextAlignment(RenderText.ALIGN_CENTER);
		
		renderText(self.textPositionX+(self.hudWidth*0.25), self.textPositionY, self.textHigh, string.format("%s", g_i18n:getText("ALOE_ARM")));
		renderText(self.textPositionX+(self.hudWidth*0.75), self.textPositionY, self.textHigh, string.format("%s", g_i18n:getText("ALOE_TOOL")));
		renderText(self.textPositionX+(self.hudWidth*0.5), self.text2PositionY, self.text2High, string.format("%s", g_i18n:getText("ALOE_DETACH")));

		setTextAlignment(RenderText.ALIGN_LEFT);
		
		if self.allowsDetachingArm then
			self.leftGreenHUD:render();
		else
			self.leftRedHUD:render();	
		end;
		
		if self.allowsDetachingTool then
			self.rightGreenHUD:render();
		else
			self.rightRedHUD:render();	
		end;	
	end;
	
	g_currentMission:addHelpButtonText(g_i18n:getText("ALOE_SHOWDETACH_HUD"), InputBinding.IMPLEMENT_EXTRA4);
	
	if self.variableColors ~= nil then
		g_currentMission:addExtraPrintText(g_i18n:getText("ALOE_FRONTLOADER_HELP"));	
	end;
end

function AloeFrontloader:detachImplement()
	self.afterDetachTimer = 1000;
end;