// RealmCatalogResource.java
// $Id: RealmCatalogResource.java,v 1.3 1997/07/23 15:02:33 ylafon Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.auth;

import java.util.*;
import java.io.*;
import w3c.tools.store.*;
import w3c.jigsaw.resources.*;
import w3c.jigsaw.http.*;

public class RealmCatalogResource extends HTTPResource
                                  implements ContainerInterface {
    protected httpd server = null;
    protected RealmsCatalog catalog = null;
				      
    // No direct access to the underlying store

    public boolean hasResourceStore() {
	return false;
    }
    
    public ResourceStore getResourceStore(ResourceStoreHolder holder) {
	return null;
    }
    
    public Enumeration enumerateResourceIdentifiers(boolean all) {
	if( catalog == null ) {
	    catalog = server.getRealmsCatalog() ;
	}
	return catalog.enumerateRealmNames();
    }
    
    public Resource lookup(String name) {
	if( catalog == null ) {
	    catalog = server.getRealmsCatalog() ;
	}
	LookupState ls;
	try {
	    ls = new LookupState(name);
	} catch (HTTPException ex) {
	    return null;
//	    throw new InvalidResourceException("Internal Server Error");
	}
	String realmName = ls.getNextComponent();
	AuthRealm realm = catalog.loadRealm(realmName);
	if( !ls.hasMoreComponents())
	    return new AuthRealmResource(realm);
	String user = ls.getNextComponent();
	if( ls.hasMoreComponents()) {
	    // throw new InvalidResourceException("URL too long");
	    return null;
	}
	return realm.loadUser(user);
    }

    public void delete(String name) {
	if( catalog == null ) {
	    catalog = server.getRealmsCatalog() ;
	}
	catalog.unregisterRealm(name);
    }
    
    public void registerResource(String name,
				 Resource resource,
				 Hashtable defs) {
	if( catalog == null ) {
	    catalog = server.getRealmsCatalog() ;
	}
	if( resource instanceof AuthRealmResource) {
	    String repname;
	    repname = name + ".db";
	    File file = new File(server.getAuthDirectory(), repname);
	    if ( file.exists() ) {
		// fancy exception FIXME
		return;
	    }
	    catalog.registerRealm(AuthRealm.makeRealm(server, name, file));
	}
    }    
    
    public RealmCatalogResource(httpd server) {
	this.server = server;
    }
}
