
/* Josh Holtrop
 * 2008-12-04
 * CS656
 * Lab 4
 */

import java.io.File;

import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.Component;
import org.restlet.Restlet;
import org.restlet.Route;
import org.restlet.Router;
import org.restlet.data.Protocol;
import org.restlet.util.Variable;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.config.Configuration;

/**
 * This class implements the main functionality of the server for our chat program.
 */
public class ChatServer extends Application
{
    /**
     * This is our persistant object database container.
     */
    private ObjectContainer myContainer;

    public ChatServer()
    {
        /** Open and keep the db4o object container. */
        Configuration config = Db4o.configure();
        config.updateDepth(2);
        String fileName = System.getProperty("user.home")
            + File.separator + "cs656-lab4-users.dbo";
        System.out.println("Database file is: " + fileName);
        myContainer = Db4o.openFile(fileName);
    }

    /* Create application root node.
     * @see org.restlet.Application#createRoot()
     */
    @Override
    public Restlet createRoot()
    {
        Router router = new Router(getContext());

        // Add a route for user resources
        router.attach("/users", UsersResource.class);

        // Add a route for a user resource
        router.attach("/users/{id}", UserResource.class);

        return router;
    }

    public ObjectContainer getContainer()
    {
        return myContainer;
    }

    /**
     * @param args Passed in from the command line.
     */
    public static void main(String[] args)
    {
        try
        {
            // Create a component with an HTTP server connector
            Component comp = new Component();
            comp.getServers().add(Protocol.HTTP, 42842);

            // Attach the application to the default host and start it
            comp.getDefaultHost().attach("/v1", new ChatServer());
            comp.start();
        }
        catch (Exception ex)
        {
            System.out.println("Whoops, our server threw an exception while bootstrapping, details follow.");
            ex.printStackTrace();
        }
    }
}
