import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.security.MessageDigest;

//import org.apache.log4j.Logger;
//import org.apache.log4j.PropertyConfigurator;

import sun.misc.BASE64Encoder;

/*
 * Generates SHA-1 hashes for clients, responds to clients and saves MAC/SHA-1 pairs on disk
 */
public class RegistrationHandler {

	//private static Logger logger = Logger.getLogger(RegistrationHandler.class);
	public String registerClient(String client_mac_address){
		//PropertyConfigurator.configure("config.properties");
		try
		{
			String duplicate_client = "false";
			String data;
			BufferedReader br = new BufferedReader(new FileReader("registered_clients.txt"));
			BufferedWriter bw = new BufferedWriter(new FileWriter("registered_clients.txt", true));
			while((data = br.readLine()) != null){   
				if (data.contains(client_mac_address)){
					duplicate_client="true";
				}       
			}

			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(client_mac_address.getBytes("UTF-8"));
			byte[] raw = digest.digest();
			String hash = (new BASE64Encoder()).encode(raw);
			if (duplicate_client.equals("false")){
				bw.write(client_mac_address+"="+hash+"\n");
			}
			br.close();
			bw.close();
			File f = new File(hash);
			f.mkdir();
			return hash;
		}
		catch (Exception e)
		{
			//logger.info("Error writing to file");
			return "registration failed";
		}
	}
}
