/*
 * Created on 24.06.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;

import java.util.Hashtable;

import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;

/**
 * @author Eugene Prokopiev <eugene_prokopiev@mail.ru>
 * 
 */
abstract public class LdapEntryList extends EntryList {
	
	protected InitialDirContext ctx;
	
	public LdapEntryList(String url, String context, String user, String password) 
		throws EntryListException {			
		try {
			Hashtable env = new Hashtable();
			setFactories(env);
			env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, url+"/"+context);
			env.put(Context.SECURITY_PRINCIPAL, user);
			env.put(Context.SECURITY_CREDENTIALS, password);				
			ctx = new InitialDirContext(env);
			load();
		} catch (NamingException e) {
			throw new EntryListException(e.toString(true));
		}	
	}
	
	public void dispose() throws EntryListException {		
		try {
			entries.clear();
			ctx.close();
		} catch (NamingException e) {
			throw new EntryListException(e.toString(true));
		}
	}
	
	public void load() throws EntryListException {
		try {
			NamingEnumeration enum = ctx.listBindings("");		
			while (enum.hasMore()) {
				Binding binding = (Binding)enum.next();
				Entry entry = getEntry(binding.getObject());
				innerAdd(entry);
			}
		} catch (NamingException e) {
			throw new EntryListException(e.toString(true));
		}
	}
	
	public void entryChanged(Entry entry) throws EntryListException {
		try {
			ctx.rebind("cn="+getEntryCn(entry), entry);	
			edit(entry);
		} catch (NamingException e) {
			throw new EntryListException(e.toString(true));
		}
	}	

	public void add(Entry entry) throws EntryListException {
		try {
			ctx.bind("cn="+getEntryCn(entry), entry);
			super.add(entry);
		} catch (NamingException e) {
			throw new EntryListException(e.toString(true));
		}
	}
	
	public void remove(Entry entry) throws EntryListException {
		try {
			ctx.unbind("cn="+getEntryCn(entry));
			super.remove(entry);
		} catch (NamingException e) {
			throw new EntryListException(e.toString(true));
		}
	}
	
	abstract protected void setFactories(Hashtable env);	
	abstract protected LdapEntry getEntry(Object entry);	
	abstract public Class getEntryClass();	
	abstract protected String getEntryCn(Object entry);
	
}
