writeConsole("Camera init...\n");

--- The camera class we may just want to save for later...
Camera = Entity:createSubClass();

function Camera:init()

   self:setLinkTarget("player,worldPlayer");

   self:setBlockable(false);
   self:setBlocker(false);
   self:setGravityInfluence(0);
   self:setAlpha(1);
   
   -- Appearance (editor only)
   self:setEditorVisibleOnly(true);
   self:setTexture("editoronlyentities.tga");
   self:setSpriteFrame(0, 0, 32, 32);
   
   self:setSize(32, 32);
   
   self.movingForFrames = 0;
   self.lastMoveDir = 0;
   self:setForceUpdate(true);
   self.isPermanent = true;
end

function Camera:update()
end

function Camera:postUpdate()

   -- TODO: Average position of all link targets? Might be useful to
   -- keep track of the player + something interesting, like a boss.

   local player;
   local linkTargets = self:getAllLinkTargets();

   for k, v in pairs(linkTargets) do
      player = entitiesByName[v];

      if player then
         break;
      end

   end

	if player == nil then
		return;
	end
	if player:getDead() then
		return;
	end
	
	local px, py = player:getPos();
	local mx, my = self:getPos();
	
	-- self:setPos();
	-- setCameraPos(self:getPos());
	
	--if py > 0 then
		--py = 0;
	--end
	
	--if py < -2304 then
		--py = -2304;
	--end
	
	--if px < 0 then
		--px = 0;
	--end
	
	--if px > 3072 then
		--px = 3072;
	--end
	
	local dt = 64;
	local movedThisFrame = false;
	
	if px - mx > dt then
		mx = mx + (px - mx) - dt;
		movedThisFrame = true;
		self.lastMoveDir = 1;
	end
	if px - mx < dt * -1 then
		mx = mx + (px - mx) + dt;
		movedThisFrame = true;
		self.lastMoveDir = 0;
     end

	if py - my > dt then
		my = my + (py - my) - dt;
		movedThisFrame = true;
		self.lastMoveDir = 1;
	end
	if py - my < dt * -1 then
		my = my + (py - my) + dt;
		movedThisFrame = true;
		self.lastMoveDir = 0;
	end

	if movedThisFrame then
		self.movingForFrames = self.movingForFrames + 1;
		if self.movingForFrames > 64 then
			self.movingForFrames = 64;
		end
	else
		self.movingForFrames = self.movingForFrames - 1;
		if self.movingForFrames < 0 then
			self.movingForFrames = 0;
		end
	end
	
	self.movingForFrames = 0;
	
	self:setPos(mx, my);
	
	local moveScale = 8;
	if self.lastMoveDir == 1 then
		setCameraPos(mx + self.movingForFrames * moveScale, my);
	else
		setCameraPos(mx - self.movingForFrames * moveScale, my);
	end
end

mainCamera = Camera:create();
mainCamera:setName("camera");



