package org.objectweb.jonas.jtests.servlets.endpoint;

import java.util.Hashtable;
import java.util.Map;

public class AddressBookImpl implements AddressBook {

    /**
     * Hack !! used to keep a state in this ws !
     */
    private static Map addresses = null;

    private static void initAddresses() {
        addresses = new Hashtable();
        Address a = new Address();
        a.setName("JOnAS");
        a.setCompany("ObjectWeb Consortium");
        a.setVersion(4.0f);
        addresses.put(a.getName(), a);
    }

    public AddressBookImpl() {
        if (addresses == null) {
            initAddresses();
        }
    }

    public void addAddress(Address addr) throws AddressBookException {
        if (isPresent(addr.getName())) {
            throw new AddressBookException("Address " + addr + " already present in Book");
        }

        addresses.put(addr.getName(), addr);
    }

    public Address getAddress(String name) {
        return (Address) addresses.get(name);
    }

    public Address[] getAddresses() {
        Address[] exported = new Address[addresses.size()];
        return (Address[]) addresses.values().toArray(exported);
    }
    
    public boolean isPresent(String name) {
        return (getAddress(name) != null);
    }

    public void reset() {
        addresses = null;
    }
}
