/*
 * Caveworld
 *
 * Copyright (c) 2014 kegare
 * https://github.com/kegare
 *
 * This mod is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL.
 * Please check the contents of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt
 */

package com.kegare.caveworld.handler;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.Teleporter;
import net.minecraft.world.WorldServer;

import com.kegare.caveworld.core.CaveAchievementList;
import com.kegare.caveworld.core.CaveMiningPlayer;
import com.kegare.caveworld.core.Caveworld;
import com.kegare.caveworld.core.Config;
import com.kegare.caveworld.world.TeleporterCaveworld;

import cpw.mods.fml.common.IPlayerTracker;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;

public class CavePlayerTracker implements IPlayerTracker
{
	@Override
	public void onPlayerLogin(EntityPlayer player) {}

	@Override
	public void onPlayerLogout(EntityPlayer player) {}

	@Override
	public void onPlayerRespawn(EntityPlayer player)
	{
		if (player instanceof EntityPlayerMP)
		{
			EntityPlayerMP thePlayer = (EntityPlayerMP)player;
			int dim = thePlayer.dimension;

			if (dim == Config.dimensionCaveworld)
			{
				if (thePlayer.getBedLocation(dim) == null)
				{
					MinecraftServer server = Caveworld.proxy.getServer();
					WorldServer world = server.worldServerForDimension(0);
					Teleporter teleporter = new TeleporterCaveworld(world, false, false);

					server.getConfigurationManager().transferPlayerToDimension(thePlayer, 0, teleporter);
				}
				else if (!Config.hardcoreEnabled)
				{
					int level = CaveMiningPlayer.get(thePlayer).getMiningLevel();

					if (level <= 0 || thePlayer.getRNG().nextInt(level) == 0)
					{
						thePlayer.setSpawnChunk(null, true, dim);
					}
				}
			}
		}
	}

	@Override
	public void onPlayerChangedDimension(EntityPlayer player)
	{
		if (player instanceof EntityPlayerMP)
		{
			EntityPlayerMP thePlayer = (EntityPlayerMP)player;
			WorldServer world = thePlayer.getServerForPlayer();

			if (thePlayer.dimension == Config.dimensionCaveworld)
			{
				NBTTagCompound data = thePlayer.getEntityData();

				if (!data.hasKey("Caveworld:LastTeleportTime") || data.getLong("Caveworld:LastTeleportTime") + 18000L < world.getTotalWorldTime())
				{
					PacketDispatcher.sendPacketToPlayer(CavePacketHandler.getPacketCaveMusic("caveworld:ambient.cave"), (Player)thePlayer);
				}

				data.setLong("Caveworld:LastTeleportTime", world.getTotalWorldTime());

				thePlayer.triggerAchievement(CaveAchievementList.caveworld.orNull());
			}
			else
			{
				PacketDispatcher.sendPacketToPlayer(CavePacketHandler.getPacketCaveMusic("stop"), (Player)player);
			}
		}
	}
}