--
-- BuyableTwinWheels
-- Specialization for Buyable Twin Wheels
--
-- @author  	Manuel Leithner (SFM-Modding)
-- @version 	v3.0
-- @date  		30/10/10
-- @history:	v1.0 - Initial version
--				v2.0 - added network support, changed update to updateTick
--				v3.0 - Added dynamic collision support, ls13-ready
--				v3.1 - Some modifications (by fruktor) 
--
-- free for noncommerical-usage
--

BuyableTwinWheels = {};

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

function BuyableTwinWheels:load(xmlFile)

	self.twinWheelTriggerCallback = BuyableTwinWheels.twinWheelTriggerCallback;
	self.wheelDelete = BuyableTwinWheels.wheelDelete;
	self.assembleWheels = SpecializationUtil.callSpecializationsFunction("assembleWheels");
	self.disassembleWheels = SpecializationUtil.callSpecializationsFunction("disassembleWheels");

	self.checkString = Utils.getNoNil(getXMLString(xmlFile, "vehicle.twinWheels#checkString"), "standart");
	self.usingTrigger = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.twinWheels#activationTrigger"));
	
	addTrigger(self.usingTrigger, "twinWheelTriggerCallback", self);
    self.deleteListenerId = addDeleteListener(self.usingTrigger, "wheelDelete", self);
	
	self.belts = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.twinWheels#belts"));
	self.side  = getXMLString(xmlFile, "vehicle.twinWheels#side");
	
    self.buyableWheels = {};
    local i = 0;
    while true do
        local wheelnamei = string.format("vehicle.twinWheels.wheel(%d)", i);
        local wheel = {};
        local wheelIndex = getXMLInt(xmlFile, wheelnamei .. "#wheelIndex");
        if wheelIndex == nil then
            break;
        end;
		
		wheel.wheelIndex = wheelIndex;
		wheel.node = Utils.indexToObject(self.components, getXMLString(xmlFile, wheelnamei .. "#node"));
		wheel.collision = Utils.indexToObject(self.components, getXMLString(xmlFile, wheelnamei .. "#collision"));
		if self.isServer then		
			setRigidBodyType(wheel.collision, "NoRigidBody");
		else
			delete(wheel.collision);
			wheel.collision = nil;
		end;
		wheel.savePosition = Utils.indexToObject(self.components, getXMLString(xmlFile, wheelnamei .. "#savePosition"));
		table.insert(self.buyableWheels, wheel);
		i = i + 1;
	end;

	self.loadedCoords = nil;
	self.twinWheelsUser = nil;
	
	
	--DURAL
	local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.twinWheels#comTrans"));
	self.realComTrans = {x=Utils.getNoNil(x,0), y=Utils.getNoNil(y,0), z=Utils.getNoNil(z,0)};
	
	local mass = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.twinWheels#mass"), 0);
	self.realAdditionalMass = mass;
	
	--# fruktor
	self.vehicleFlotationInc = Utils.getNoNil( getXMLFloat(xmlFile, "vehicle.twinWheels#vehicleFlotationInc"), 0);
	self.tyreGripInc = Utils.getNoNil( getXMLFloat(xmlFile, "vehicle.twinWheels#tyreGripInc"), 0); 
	
end;



function BuyableTwinWheels:delete()
	if self.twinWheelsUser ~= nil then
		self.twinWheelsUser:onDisassembling(true);
		for _,twinWheel in pairs(self.buyableWheels) do
			delete(twinWheel.node);
			if self.isServer then
				delete(twinWheel.collision);
			end;
		end;
		self.buyableWheels = {};
	end;
    removeTrigger(self.usingTrigger);
end;

function BuyableTwinWheels:wheelDelete()
    removeDeleteListener(self.usingTrigger, self.deleteListenerId);
end;

function BuyableTwinWheels:readStream(streamId, connection)
	local id = streamReadInt32(streamId);
	if id ~= -1 then
		local twinWheelsUser = networkGetObject(id);
		if twinWheelsUser ~= nil then
			self:assembleWheels(twinWheelsUser, true);
		end;
	end;
end;

function BuyableTwinWheels:writeStream(streamId, connection)
	local idToWrite = -1;
	if self.twinWheelsUser ~= nil then
		idToWrite = networkGetObjectId(self.twinWheelsUser);
	end;
	streamWriteInt32(streamId, idToWrite);
end;

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

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

function BuyableTwinWheels:update(dt)
end;

function BuyableTwinWheels:updateTick(dt)

	-- try to load saved twinwheels
	if self.loadedCoords ~= nil then
		for k,steerable in pairs(g_currentMission.steerables) do
			local a,b,c = getWorldTranslation(steerable.rootNode);
			local distance = Utils.vector3Length(self.loadedCoords.x-a, self.loadedCoords.y-b, self.loadedCoords.z-c);
			if distance < 0.15 then				
				self:assembleWheels(steerable);
				break;
			end;
		end;
		self.loadedCoords = nil;
	end;
end;

function BuyableTwinWheels:draw()	
end;

function BuyableTwinWheels:twinWheelTriggerCallback(triggerId, otherId, onEnter, onLeave, onStay, otherShapeId)
	local vehicle = g_currentMission.controlledVehicle;
	if vehicle ~= nil then
		if onEnter then		
			if vehicle.rootNode == otherId then
				if vehicle.buyableTwinWheels ~= nil then
					if vehicle.buyableTwinWheels.checkString == self.checkString then
						if self.twinWheelsUser ~= nil then
							if self.twinWheelsUser == vehicle then
								vehicle.buyableTwinWheels.wheelsInRange = self;
							end;
						else
							vehicle.buyableTwinWheels.wheelsInRange = self;
						end;
					end;
				end;
			end;
		elseif onLeave then		
			if otherId == vehicle.rootNode then
				if vehicle.buyableTwinWheels ~= nil then
					vehicle.buyableTwinWheels.wheelsInRange = nil;
				end;
			end;
		end;
	end;
end;

function BuyableTwinWheels:assembleWheels(vehicle, noEventSend)
	BuyableTwinWheelsAttachEvent.sendEvent(self, vehicle, noEventSend);

	if self.belts ~= nil then
		setVisibility(self.belts, false);
	end;
	if self.twinWheelsUser == nil then
		if vehicle.buyableTwinWheels ~= nil then
			self.twinWheelsUser = vehicle;	
			for l,twinWheel in pairs(self.buyableWheels) do 				
				for k,wheel in pairs(vehicle.wheels) do
					--if k == l then					
					if k == twinWheel.wheelIndex then									-- !
						link(wheel.driveNode, twinWheel.node);
						local x,y,z = getWorldTranslation(wheel.twinWheelAttacher);							
						x,y,z = worldToLocal(wheel.driveNode, x,y,z);
						setTranslation(twinWheel.node,x,y,z);
						if self.isServer then
							link(getRootNode(), twinWheel.collision);
							--local x,y,z = getWorldTranslation(wheel.driveNode);
							local x,y,z = getWorldTranslation(wheel.twinWheelAttacher);							
							x,y,z = worldToLocal(getParent(twinWheel.collision), x,y,z);
							setTranslation(twinWheel.collision,x,y,z);
							local dx,dy,dz = localDirectionToWorld(wheel.twinWheelAttacher, 0,0,1);
							local lx,ly,lz = worldDirectionToLocal(getParent(twinWheel.collision), dx,dy,dz);
							setDirection(twinWheel.collision, lx,ly,lz, 0,1,0);
							setRigidBodyType(twinWheel.collision, "Dynamic");							
							local constr = JointConstructor:new();
							constr:setActors(wheel.rootNode, twinWheel.collision);
							constr:setJointTransforms(wheel.twinWheelAttacher, twinWheel.collision);
							constr:setRotationLimit(0, 0, 0);
							constr:setRotationLimit(1, 0, 0);
							constr:setRotationLimit(2, 0, 0);
							constr:setTranslationLimit(0, true, 0, 0);
							constr:setTranslationLimit(1, true, 0, 0);
							constr:setTranslationLimit(2, true, 0, 0);
							twinWheel.joint = constr:finalize();
							setPairCollision(wheel.rootNode, twinWheel.collision, false);
						end;
						break;
					end;
				end;
			end;

			if self.isServer then
				for _, twinWheel in pairs(self.buyableWheels) do
					for _, otherTwinWheels in pairs(self.buyableWheels) do
						if twinWheel.collision ~= otherTwinWheels.collision then
							setPairCollision(twinWheel.collision, otherTwinWheels.collision, false);
						end;
					end;
					
					for _, component in pairs(self.components) do
						setPairCollision(component.node, twinWheel.collision, false);
					end;
				end;
			end;
			
			--# fruktor
			if self.twinWheelsUser.isRealistic then
				self.twinWheelsUser.realVehicleFlotationFx = self.twinWheelsUser.realVehicleFlotationFx + self.vehicleFlotationInc;
				self.twinWheelsUser.realTyreGripFx = self.twinWheelsUser.realTyreGripFx + self.tyreGripInc;
			end;			
			
			self.twinWheelsUser:onAssembling(self);
		end;
	end;
end;

function BuyableTwinWheels:disassembleWheels(noEventSend)
	BuyableTwinWheelsDetachEvent.sendEvent(self, noEventSend);

	self.twinWheelsUser:onDisassembling();

	if self.belts ~= nil then
		setVisibility(self.belts, true);
	end;
	
	for k,wheel in pairs(self.buyableWheels) do
		if self.isServer then
			removeJoint(wheel.joint);
			setRigidBodyType(wheel.collision, "NoRigidBody");
			link(wheel.savePosition, wheel.collision);
			setRotation(wheel.collision, 0,0,0);
			setTranslation(wheel.collision, 0,0,0);
		end;
		
		link(wheel.savePosition, wheel.node);
		setRotation(wheel.node, 0,0,0);
		setTranslation(wheel.node, 0,0,0);
	end;	
	
	--# fruktor
	if self.twinWheelsUser.isRealistic then
		self.twinWheelsUser.realVehicleFlotationFx = self.twinWheelsUser.realVehicleFlotationFx - self.vehicleFlotationInc;
		self.twinWheelsUser.realTyreGripFx = self.twinWheelsUser.realTyreGripFx - self.tyreGripInc;
	end;		
	
	self.twinWheelsUser = nil;	
end;


function BuyableTwinWheels:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)

	if not resetVehicles then
		local valueStr = getXMLString(xmlFile, key.."#attacherCoords");		
		if valueStr ~= nil then
			local x,y,z = Utils.getVectorFromString(valueStr);
			self.loadedCoords = {x = x,y = y,z = z};			
		end;
	end; 

    return BaseMission.VEHICLE_LOAD_OK;
end;

function BuyableTwinWheels:getSaveAttributesAndNodes(nodeIdent)	
    local attributes = nil;
	
	if self.twinWheelsUser ~= nil then
		local x,y,z = getWorldTranslation(self.twinWheelsUser.rootNode);
		attributes = 'attacherCoords="'.. x .. " " .. y .. " " .. z ..'"';
	end;
	
    return attributes, nil;
end;

BuyableTwinWheelsAttachEvent = {};
BuyableTwinWheelsAttachEvent_mt = Class(BuyableTwinWheelsAttachEvent, Event);

InitEventClass(BuyableTwinWheelsAttachEvent, "BuyableTwinWheelsAttachEvent");

function BuyableTwinWheelsAttachEvent:emptyNew()
    local self = Event:new(BuyableTwinWheelsAttachEvent_mt);
    return self;
end;

function BuyableTwinWheelsAttachEvent:new(vehicle, attacherVehicle)
    local self = BuyableTwinWheelsAttachEvent:emptyNew()
    self.vehicle = vehicle;
	self.attacherVehicle = attacherVehicle;
    return self;
end;

function BuyableTwinWheelsAttachEvent:readStream(streamId, connection)
    local id = streamReadInt32(streamId);
	local attacherId = streamReadInt32(streamId);
	self.attacherVehicle = networkGetObject(attacherId);
    self.vehicle = networkGetObject(id);
    self:run(connection);
end;

function BuyableTwinWheelsAttachEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.vehicle));
	streamWriteInt32(streamId, networkGetObjectId(self.attacherVehicle));
end;

function BuyableTwinWheelsAttachEvent:run(connection)
	self.vehicle:assembleWheels(self.attacherVehicle, true);
    if not connection:getIsServer() then
        g_server:broadcastEvent(BuyableTwinWheelsAttachEvent:new(self.vehicle, self.attacherVehicle), nil, connection, self.object);
    end;
end;


function BuyableTwinWheelsAttachEvent.sendEvent(vehicle, attacherVehicle, noEventSend)
	if noEventSend == nil or noEventSend == false then
		if g_server ~= nil then
			g_server:broadcastEvent(BuyableTwinWheelsAttachEvent:new(vehicle, attacherVehicle), nil, nil, vehicle);
		else
			g_client:getServerConnection():sendEvent(BuyableTwinWheelsAttachEvent:new(vehicle, attacherVehicle));
		end;
	end;
end;


BuyableTwinWheelsDetachEvent = {};
BuyableTwinWheelsDetachEvent_mt = Class(BuyableTwinWheelsDetachEvent, Event);

InitEventClass(BuyableTwinWheelsDetachEvent, "BuyableTwinWheelsDetachEvent");

function BuyableTwinWheelsDetachEvent:emptyNew()
    local self = Event:new(BuyableTwinWheelsDetachEvent_mt);
    return self;
end;

function BuyableTwinWheelsDetachEvent:new(vehicle)
    local self = BuyableTwinWheelsDetachEvent:emptyNew()
    self.vehicle = vehicle;
    return self;
end;

function BuyableTwinWheelsDetachEvent:readStream(streamId, connection)
    local id = streamReadInt32(streamId);
    self.vehicle = networkGetObject(id);
    self:run(connection);
end;

function BuyableTwinWheelsDetachEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.vehicle));
end;

function BuyableTwinWheelsDetachEvent:run(connection)
	self.vehicle:disassembleWheels(true);
    if not connection:getIsServer() then
        g_server:broadcastEvent(BuyableTwinWheelsDetachEvent:new(self.vehicle), nil, connection, self.object);
    end;
end;


function BuyableTwinWheelsDetachEvent.sendEvent(vehicle, noEventSend)
	if noEventSend == nil or noEventSend == false then
		if g_server ~= nil then
			g_server:broadcastEvent(BuyableTwinWheelsDetachEvent:new(vehicle), nil, nil, vehicle);
		else
			g_client:getServerConnection():sendEvent(BuyableTwinWheelsDetachEvent:new(vehicle));
		end;
	end;
end;


