--
-- BuyableTwinWheels
-- Specialization for Buyable Twin Wheels
--
-- @author  	Manuel Leithner (SFM-Modding)
-- @version 	v2.0
-- @date  		15/10/10
-- @history:	v1.0 - Initial version
--				v2.0 - added network support, changed update to updateTick
--

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.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"));
		-- collision bug fix: on initial wheel assembling no collision is set
		setRigidBodyType(wheel.collision, "Kinematic");
		setRigidBodyType(wheel.collision, "NoRigidBody");
		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;
end;

function BuyableTwinWheels:delete()
	if self.twinWheelsUser ~= nil then
		self.twinWheelsUser:onDisassembling(true);
		for _,twinWheel in pairs(self.buyableWheels) do
			delete(twinWheel.node);
			delete(twinWheel.collision);
		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 k,wheel in pairs(vehicle.wheels) do
				for l,twinWheel in pairs(self.buyableWheels) do 
					if k == l then	
						unlink(twinWheel.node);
						unlink(twinWheel.collision);
						link(wheel.driveNode, twinWheel.node);	
						link(getParent(wheel.repr), twinWheel.collision);	
						local x,y,z = getWorldTranslation(wheel.driveNode);
						x,y,z = worldToLocal(getParent(twinWheel.collision), x,y,z);
						setTranslation(twinWheel.collision,x,y,z);
						--setRigidBodyType(twinWheel.collision, "Kinematic");
						break;
					end;
				end;
			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
		setRigidBodyType(wheel.collision, "NoRigidBody");
		unlink(wheel.collision);
		unlink(wheel.node);
		setRotation(wheel.collision, 0,0,0);
		setTranslation(wheel.collision, 0,0,0);
		link(wheel.savePosition, wheel.collision);
		link(wheel.collision, wheel.node);
	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;




