/*
 * Created on 30.04.2004
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 */
 
package networkconsole.datamodel.persistance;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.spi.DirObjectFactory;

import networkconsole.datamodel.LdapHostEntry;

/**
 * @author Eugene Prokopiev <john@rmts.donpac.ru>
 * 
 */
public class LdapHostObjectFactory implements DirObjectFactory {

	public Object getObjectInstance(
		Object obj,
		Name name,
		Context nameCtx,
		Hashtable environment,
		Attributes attrs)
		throws Exception {

		Attribute oc = (attrs != null ? attrs.get("objectClass") : null);
		if (oc != null && oc.contains("dhcpHost") 
			&& oc.contains("internetAccess") 
			&& oc.contains("hostsInfo")) {

			LdapHostEntry host = new LdapHostEntry((String)attrs.get("cn").get());
						
			String dhcpIPAddress = "";			
			Attribute dhcpStatements = attrs.get("dhcpStatements");
			for(int i=0; i<dhcpStatements.size(); i++) {
				String dhcpStatement = (String)dhcpStatements.get(i);
				if (dhcpStatement.startsWith("fixed-address "))
					dhcpIPAddress = dhcpStatement.replaceFirst("fixed-address ", "");	
			}
			host.setDhcpIPAddress(dhcpIPAddress);
			
			String dhcpHWAddress = 
				((String)attrs.get("dhcpHWAddress").get()).replaceFirst("ethernet ", "");			
			host.setDhcpHWAddress(dhcpHWAddress);
			
			host.setAllowNat(
				(((String)attrs.get("allowNat").get()).equals("TRUE"))?(new Boolean(true)):(new Boolean(false)));
			host.setAllowProxy(
				(((String)attrs.get("allowProxy").get()).equals("TRUE"))?(new Boolean(true)):(new Boolean(false)));
			host.setForceProxy(
				(((String)attrs.get("forceProxy").get()).equals("TRUE"))?(new Boolean(true)):(new Boolean(false)));
			
			if (attrs.get("comment") != null)
				host.setComment((String)attrs.get("comment").get());
			else
				host.setComment("");
				
			return host;
		}
		return null;

	}

	public Object getObjectInstance(
		Object obj,
		Name name,
		Context ctx,
		Hashtable env)
		throws Exception {
		
		return null;
	}

}
