import musicServer.*;
import org.omg.CORBA.*;


/**
 * Main server class
 */
public final class MusicServer extends _MusicServerIImplBase {
    private static BOA              _boa;
    private MusicCollectionHolder   _musicCollectionHolder;

    public MusicServer() {
        super("MusicServer");
        _musicCollectionHolder = new MusicCollectionHolder(_boa);
    }

    /**
     * Invoked by the client when he wants to attempt a login
     */
    public MusicCollectionI obtainCollection(String sUserName, String sPassword) throws NoSuchUserException {
        MusicCollectionI collection = _musicCollectionHolder.obtainCollection(sUserName, sPassword);
        if(collection == null) throw new NoSuchUserException("Invalid Login Information");

        _boa.obj_is_ready(collection);
        return collection;
    }

    /**
     * Invoked by the client when he wants to create a new
     * MusicCollectionI object.
     */
    public MusicCollectionI createCollection(String sUserName, String sPassword) throws UserIDExistsException {
        if(_musicCollectionHolder.doesUserNameExist(sUserName)) {
            throw new UserIDExistsException(sUserName+" is already in use");
        }

        MusicCollectionI collection = new MusicCollection(sUserName, sPassword, _boa);
        _boa.obj_is_ready(collection);
        _musicCollectionHolder.addMusicCollection(collection);

        return collection;
    }

    /**
     * Helper method that obtains an AlbumQueryS
     * object populated with dummy data.
     */
    public AlbumQueryS obtainEmptyQuery() {
        return new AlbumQueryS("", "", 0f, MediaType.NOT_SPECIFIED);
    }

    /**
     * Performs an exhaustive search of all available
     * catalogs. Demonstrates the callback design pattern.
     */
    public void searchCatalog(AlbumQueryS query, RequestorI requestor) {
        AlbumSearcher searcher = new AlbumSearcher(query, requestor, _boa);
        searcher.start();
    }

    /**
     * Invoked by the client when he wants to logout, deactivates
     * all activated objects.
     */
    public void logOut(MusicCollectionI collection) {
        Deactivator deactivator = new Deactivator(collection, _boa);
        deactivator.start();
    }

    public void saveCollection() {
        _musicCollectionHolder.saveCollection();
    }

    public static void main(String[] args) {
        ORB orb = ORB.init();
        _boa = orb.BOA_init();

        MusicServer server = new MusicServer();

        _boa.obj_is_ready(server);
        _boa.impl_is_ready();
    }
}
