
function stringSplit(str, c)
	local chunks = {};
	local currentChunk = "";
	local chunkNum = 1;
	
	for i = 1, string.len(str) do
		local substr = string.sub(str, i, i)
		if substr == c then
			chunks[chunkNum] = currentChunk;
			currentChunk = "";
			chunkNum = chunkNum + 1;
		else
			currentChunk = currentChunk..substr;
		end
	end
	chunks[chunkNum] = currentChunk;
	
	return chunks;
end

Teleporter = Activatable:createSubClass();


--function Teleporter:setDestination(dest)
	--if dest == nil then
		--self:setLabel("Teleport:\n<unknown>");
		--return;
	--end

	--local chunks = stringSplit(dest, " ");
	--self.level = chunks[1];
	--self.refpoint = chunks[2];
	--if self.level and self.refpoint then
		--self:setLabel("Teleport:\n"..self.level.."\n"..self.refpoint);
	--else
		--self:setLabel("Teleport:\n<unknown>");
	--end
	----self.destination = dest;
--end

function Teleporter:init()

   Activatable.init(self);

   self:setLabelFont("data/font1.png");
   self:setTexture("data/teleporter.png");
   self:setSize(64, 128);
   self:setSpriteFrame(0, 0, 64, 128);
   self:setDepth(1);
   
   -- This needs to become true to enable teleportation.
   -- (The player needs to move OFF the teleporter before moving back on.)
   self.untouched = false;
   self.teleportStarted = false;

   self.totalCountDown = 20;
   self.teleportCountDown = self.totalCountDown;
   
   self.editorProperties = {destLevel="", destEntity=""};
   self.untouched = false;
   self.alreadyCleared = false;
end

function Teleporter:save()
	return {
		--untouched = self.untouched,
		teleportStarted = self.teleportStarted,
		teleportCountDown = self.teleportCountDown
	};
end

function Teleporter:initFromSave(saveData)

   Activatable.init(self);

   --self.untouched = saveData.untouched;
   --self.teleportStarted = saveData.teleportStarted;
   --self.teleportCountDown = saveData.teleportCountDown;
   self.untouched = false;
   self.teleportStarted = false;
   self.totalCountDown = 20;
   self.teleportCountDown = self.totalCountDown;
   self.alreadyCleared = false;
end

function Teleporter:update()

   Activatable.update(self)

   if self.editorProperties.destLevel and self.editorProperties.destEntity then
      self:setLabel("Teleport:\n"..self.editorProperties.destLevel.."\n"..self.editorProperties.destEntity);
   end
   self:setAlpha((math.sin(self:getAge() / 10) + 1) / 2);
   
   local screenFade = entitiesByName["screenFade"];
   
   if self.teleportStarted then
      local player = entitiesByName["player"];

      if not player then
         player = entitiesByName["worldPlayer"];
      end
      
      self.teleportCountDown = self.teleportCountDown - 1;
      
      --local fadeAmount = self.teleportCountDown / 10;
      --if(fadeAmount < 0) then
      --   fadeAmount = 0;
      --end
      --setSubtractiveFade(fadeAmount, fadeAmount, fadeAmount);

      --if screenFade then
      --	screenFade:setAlpha(1 - (self.teleportCountDown / 10));
      --end
      
      -- Fade out the player for a graphical effect.
      if player then
         player:setAlpha(self.teleportCountDown / 10);
      end
      
      -- Stage 1 - Clear out all Entities that aren't the player or this.
      if self.teleportCountDown < 0 and not self.alreadyCleared then
         -- Save the old level, except the player (which will be in the new one)
         
         -- FIXME: This will break if we ever want to load stuff from
         --   a file as part of something other than a normal level
         --   transition! In the meantime we need it for debugging,
         --   though.
         if lastLoadedFile then
            globalData.currentLevel = lastLoadedFile;
         end
         
         saveEntities(globalData.currentLevel, "player", "worldPlayer");
         
         for i = 0, 5, 1 do
            clearLayer(i, "player", "worldPlayer", self:getName());
         end
         self.alreadyCleared = true;
      end
      
      -- Stage 2 - Switch levels
      if self.teleportCountDown < -1 then
         local otherEnt = entitiesByName["player"];
         
         if not otherEnt then
            otherEnt = entitiesByName["worldPlayer"];
         end

         globalData.currentLevel = self.editorProperties.destLevel;
         loadTiles(self.editorProperties.destLevel..".tiles.rle");
         for i = 0, 5, 1 do
            clearLayer(i, "player", "worldPlayer");
         end
         loadEntities(self.editorProperties.destLevel);

         local realRefpoint = entitiesByName[self.editorProperties.destEntity];
         if realRefpoint then
            local x, y = realRefpoint:getPos();
            local sx, sy = realRefpoint:getSize();
            local px, py = otherEnt:getSize();
            y = y - sy / 2;
            y = y + py / 2;
            otherEnt:setPos(x, y);
         end
         
         if player then
            player:setAlpha(1);
         end
         
         --if screenFade then
         --	screenFade:startFadeIn();
         --end
         fade_fadeWhite = false;

         -- Save the new level, with the player.
         saveEntities(globalData.currentLevel, self:getName());
         
         -- Save the new globalData reflecting the new level status.
         saveTable("globaldata.xml", globalData);
      end
   end
end

function Teleporter:postUpdate()

   Activatable.postUpdate(self);

   if not self.touchedThisFrame then
      self.untouched = true;
   end
   
   self.touchedThisFrame = false;

end

function Teleporter:collided_derp(otherEntName)

   if otherEntName == "player" or otherEntName == "worldPlayer" then
      self.touchedThisFrame = true;
   end
   
   if self.untouched then
      
      if otherEntName == "player" or otherEntName == "worldPlayer" then

         -- TODO: Wait for activation for this.

         self.teleportStarted = true;
         
         --writeConsole("Teleporting...\n");

         fade_fadeWhite = true;
         fade_speed = 1 / self.totalCountDown;

      end
   end
end

function Teleporter:activated()
   self.teleportStarted = true;   
   fade_fadeWhite = true;
   fade_speed = 1 / self.totalCountDown;
end


registerSpawn("Teleporter");
createSpawnType("TeleporterSpawn", Teleporter, "data/teleporter.png", {x1=0, y1=0, x2=64, y2=128}, {destLevel="", destEnt=""});

