-- by modelleicher
-- www.schwabenmodding.bplaced.net
-- OldtimerFL
-- sorgt für realistisches Ausklinken der Frontladerschaufel wie bei den alten Frontladern das so üblich war.
-- V2: Bug nach Verkauf einer im ausgekippten Zustand befindlichen Gabel bzw. in selbigem Zustand abgehängten Gabel
-- wurde behoben.

-- V3: LS13 Ready, Ausklinken auch möglich wenn nicht der Traktor angewählt ist.
-- V3: FS13 ready, works fine if tractor is not selected (since mostly the implement is selected for frontloader work)
-- Date of edit / Datum der Änderung: 14/09/2013

OldtimerFL = {};

function OldtimerFL.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function OldtimerFL:load(xmlFile)
    self.setFLState = OldtimerFL.setFLState;
	self.implementReference = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.OldtimerFrontloader#referencePoint"));
	
    self.isFixed = true;  
	self.checkDistance = false;
	self.debugPoints = false;
end;

function OldtimerFL:delete()
end;

function OldtimerFL:readStream(streamId, connection)  
     self:setFLState(streamReadBool(streamId), true);  
end;
function OldtimerFL:writeStream(streamId, connection)  
    streamWriteBool(streamId, self.isFixed);  
end;

function OldtimerFL:mouseEvent(posX, posY, isDown, isUp, button)
end;
function OldtimerFL:keyEvent(unicode, sym, modifier, isDown)   
end;

function OldtimerFL:setFLState(state, noEventSend)  
    setFLstateEvent.sendEvent(self, state, noEventSend);	
    self.isFixed = state; 
end;

function OldtimerFL:update(dt)
    if self:getIsActive() and self.isEntered then  -- change from self:getIsActiveForInput() for FS13, so it works if implement is selected
  		if InputBinding.hasEvent(InputBinding.FLAusklinken) then 
		   if self.isFixed == true then
		       self:setFLState(false);
		   end;
        end;		
    end; 
    if self:getIsActive() then
	    if self.flImplementReferencePoint ~= nil then
			if self.isFixed == true then
				setJointRotationLimit(self.attacherJoints[2].jointIndex, 2, true, 0, -0);		   
			elseif self.isFixed == false then
				setJointRotationLimit(self.attacherJoints[2].jointIndex, 2, false, Utils.degToRad(40), Utils.degToRad(-40));				 
				if self.checkDistance == false then
		        local nearestDistance = 0.2;
	            local px, py, pz = getWorldTranslation(self.implementReference);
	            local vx, vy, vz = getWorldTranslation(self.flImplementReferencePoint);
				if self.debugPoints then
					drawDebugPoint(px, py, pz, 1, 0, 0, 1);
					drawDebugPoint(vx, vy, vz, 0, 1, 0, 1);			
				end;
	            local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);	
				if distance > nearestDistance then
					self.checkDistance = true;
				end;	
                end;				
		    end;	   
	        if self.checkDistance == true then
		        local nearestDistance = 0.1;
	            local px, py, pz = getWorldTranslation(self.implementReference);
	            local vx, vy, vz = getWorldTranslation(self.flImplementReferencePoint);
				if self.debugPoints then
					drawDebugPoint(px, py, pz, 1, 0, 1, 1);
					drawDebugPoint(vx, vy, vz, 1, 1, 0, 1);					
				end;
	            local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);	
				if distance < nearestDistance then
					self:setFLState(true);
					self.checkDistance = false;
				end;	
			end;
		end;
	end;			
end;

function OldtimerFL:detachImplement(implementIndex)
	local implement = self.attachedImplements[implementIndex]
	local jointType = implement.object.attacherJoint.jointType;
	if jointType == Vehicle.JOINTTYPE_FRONTLOADER then
		self.flImplementReferencePoint = nil;
	end;
end;

function OldtimerFL:attachImplement(implement)		
	local jointType = implement.object.attacherJoint.jointType;
	if jointType == Vehicle.JOINTTYPE_FRONTLOADER then
		if implement.object.OFLreferencePoint ~= nil then
		   self.flImplementReferencePoint = implement.object.OFLreferencePoint;
		end;
	end;
end;
function OldtimerFL:draw()

end;
function OldtimerFL:onLeave()
end;


setFLstateEvent = {};
setFLstateEvent_mt = Class(setFLstateEvent, Event);
InitEventClass(setFLstateEvent, "setFLstateEvent");

function setFLstateEvent:emptyNew()  
    local self = Event:new(setFLstateEvent_mt );
    self.className="setFLstateEvent";
    return self;
end;
function setFLstateEvent:new(vehicle, state) 
    self.vehicle = vehicle;
    self.state = state;
    return self;
end;
function setFLstateEvent:readStream(streamId, connection)  
    local id = streamReadInt32(streamId); 
    self.state = streamReadBool(streamId); 
    self.vehicle = networkGetObject(id); 
    self:run(connection);  
end;
function setFLstateEvent:writeStream(streamId, connection)   
    streamWriteInt32(streamId, networkGetObjectId(self.vehicle));	
    streamWriteBool(streamId, self.state );   
end;
function setFLstateEvent:run(connection) 
    self.vehicle:setFLState(self.state, true);
	if not connection:getIsServer() then  
		g_server:broadcastEvent(setFLstateEvent:new(self.vehicle, self.state), nil, connection, self.object);
	end;
end;
function setFLstateEvent.sendEvent(vehicle, state, noEventSend)  
	if noEventSend == nil or noEventSend == false then
		if g_server ~= nil then   
			g_server:broadcastEvent(setFLstateEvent:new(vehicle, state), nil, nil, vehicle);
		else 
			g_client:getServerConnection():sendEvent(setFLstateEvent:new(vehicle, state));
		end;
	end;
end;