package ncrashed.registration.client;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.common.Configuration;
import ncrashed.registration.CommonProxy;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@SideOnly(Side.CLIENT)
public class ClientProxy extends CommonProxy 
{
	private String mLogin;
	private String mPassHash;
	
	@Override
    public String getLogin()
    {
    	return mLogin; 
    }
    
    @Override
    public String getPassHash()
    {
    	return mPassHash;
    }
    
    /*@Override
    public void initCommands()
    {
    	
    }*/
    
	@Override
	public void initConfig(File configDir)
	{
		String newPath = configDir.getAbsolutePath() + configDir.separator + CommonProxy.CONFIG_NAME;
		File configFile = new File(newPath);
		
		if(!configFile.exists())
		{
			try 
			{
				configFile.createNewFile();
			} catch (IOException e) 
			{
				throw new Error("Failed to create config file!");
			}
		}
		Configuration config = new Configuration(configFile);
		config.load();
		
		saveClientLogin(
				config.get(Configuration.CATEGORY_GENERAL, "login" ,"schoolgirl").value, 
				config.get(Configuration.CATEGORY_GENERAL, "pass" ,"123456").value
				);
		
		config.save();
		
		Minecraft.getMinecraft().session.username = mLogin + "#" + mPassHash;
	}
	
	@Override
	public void initLoginInformation()
	{
		
	}
	
	public void saveClientLogin(String login, String password)
	{
		mLogin = login;
		
		try 
		{
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytesOfMessage = password.getBytes("UTF-8");
			byte[] thedigest = md.digest(bytesOfMessage);
			mPassHash = byteArrayToHexString(thedigest);
		} catch (NoSuchAlgorithmException e) 
		{
			throw new Error("Cannot find MD5 algorithm!");
		} catch (UnsupportedEncodingException e) 
		{
			throw new Error("UTF-8 unsupported!");
		}
	}
	
	public static String byteArrayToHexString(byte[] b) 
	{
		String result = "";
		for (int i=0; i < b.length; i++) 
		{
			result +=
				Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
		}
		return result;
	}
}
