--
-- MMRearCam
--
-- Rückfahr-Kamera
--
-- by MMAgrarservice
--
-- edited 18.06.2013 upsidedown: individual inputbinding, bugfix for leaving with activated camera, transformGroup for adding camera on moving implement parts

MMRearCam = {};

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

function MMRearCam:load(xmlFile)
	self.MMRearCamPosX = 0;
	self.MMRearCamWidth = 1;
	self.MMRearCamPosY = 0;
	self.MMRearCamHeight = 1;
        self.MMRearCamFrame = Utils.getFilename("textures/MMRearCamFrame.dds", self.baseDirectory);
	self.MMRearCamFrameOverlay = Overlay:new("MMRearCamFrameOverlay", self.MMRearCamFrame, self.MMRearCamPosX, self.MMRearCamPosY, self.MMRearCamWidth, self.MMRearCamHeight);
	self.showMMRearCam = 0;
	
	self.rearCamObject = Utils.indexToObject(self.components, getXMLString(xmlFile,"vehicle.rearCam#index"));
end;

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

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

function MMRearCam:update(dt)
	if self:getIsActiveForInput(true) then
		if InputBinding.hasEvent(InputBinding.Rueckfahrkamera) then
			self.showMMRearCam = self.showMMRearCam+1;
			if self.showMMRearCam == 2 then
				self.showMMRearCam = 0;
			end;
		end;
	else
		if self.MMRearCam ~= 0 then
			self.MMRearCam = 0;
			link(self.rootNode, self.MMRearCam);
			node = getRootNode(0);
			setRootNode(node, 1);
			setViewport(1, 0, 0.02, 1, 1);
			setCamera(self.MMRearCam,1);
		end
	end;
end;

	
function MMRearCam:draw()
	if self:getIsActiveForInput(true) then
		g_currentMission:addHelpButtonText(g_i18n:getText("Rueckfahrkamera"),  InputBinding.Rueckfahrkamera);
		if self.showMMRearCam == 0 then
			self.MMRearCam = 0;
			link(self.rootNode, self.MMRearCam);
			node = getRootNode(0);
			setRootNode(node, 1);
			setViewport(1, 0, 0.02, 1, 1);
			setCamera(self.MMRearCam,1);
		elseif self.showMMRearCam == 1 then
			self.MMRearCam = createCamera("MMRearCam", 90, 0.1, 100);
			link(self.rootNode, self.MMRearCam);
			local xW,yW,zW = getWorldTranslation(self.rearCamObject)			
			local x,y,z = worldToLocal(self.rootNode,xW,yW,zW)
			setTranslation(self.MMRearCam,x,y,z);
			x,y,z = getRotation(self.rearCamObject);
			setRotation(self.MMRearCam,x,y,z);
			node = getRootNode(0);
			setRootNode(node, 1);
			setViewport(1, 0, 0.02, 1, 1);
			setCamera(self.MMRearCam,1);
			self.MMRearCamFrameOverlay:render();
		end;
	end
end;

function MMRearCam:delete()
		self.MMRearCam = 0;
		link(self.rootNode, self.MMRearCam);
		node = getRootNode(0);
		setRootNode(node, 1);
		setViewport(1, 0, 0.02, 1, 1);
		setCamera(self.MMRearCam,1);
end;

-- function MMRearCam:onLeave()
		-- self.MMRearCam = 0;
		-- link(self.rootNode, self.MMRearCam);
		-- node = getRootNode(0);
		-- setRootNode(node, 1);
		-- setViewport(1, 0, 0.02, 1, 1);
		-- setCamera(self.MMRearCam,1);
-- end;