package ncrashed.registration;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.IPlayerTracker;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.SERVER)
public class PlayerTracker implements IPlayerTracker 
{
	private class LoginInfo
	{
		String login;
		
		public LoginInfo(String login)
		{
			this.login = login;
		}
	}
	
	@Override
	public void onPlayerLogin(EntityPlayer player) 
	{
		if(FMLCommonHandler.instance().getEffectiveSide().isServer())
		{
			AuthServer server = new AuthServer(RegistrationMod.AUTH_SERVER_HOST, RegistrationMod.AUTH_SERVER_MIRROW);
			EntityPlayerMP netPlayer = (EntityPlayerMP)player;
			String login = netPlayer.username.split("#", 2)[0];
			
			String nick = login;
			
			nick = server.query("/api/nickname", "GET", new LoginInfo(login), String.class, false);
			if(nick == null)
				nick = server.query("/api/nickname", "GET", new LoginInfo(login), String.class, true);
			if(nick == null || nick.equals(""))
			{
				netPlayer.username = login;
				System.out.println("Failed to get nickname for login="+login);
				return;
			}
			
			netPlayer.username = nick;
		}
	}

	@Override
	public void onPlayerLogout(EntityPlayer player) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPlayerChangedDimension(EntityPlayer player) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPlayerRespawn(EntityPlayer player) {
		// TODO Auto-generated method stub

	}

}
