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

import java.io.IOException;
import java.util.*;

import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Resource;
import org.restlet.data.Status;
import org.restlet.resource.DomRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Variant;
import org.w3c.dom.*;

import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;

/**
 * This is a Resource class for handling users.
 *
 * You can GET a list of all users, or POST to create a new one.
 */
public class UsersResource extends Resource
{
    public UsersResource(Context context, Request request, Response response)
    {
        super(context, request, response);
        getVariants().add(new Variant(MediaType.TEXT_XML));
    }

    /**
     * Returns the parent application.
     *
     * @return the parent application.
     */
    public ChatServer getApplication()
    {
        return (ChatServer) getContext().getAttributes().get(ChatServer.KEY);
    }

    /**
     * Returns the database container.
     *
     * @return the database container.
     */
    public ObjectContainer getContainer()
    {
        return getApplication().getContainer();
    }

    /**
     * Search the database for all user resources.
     * @return a List of User references.
     */
    public List<User> getUsers()
    {
        // Create the query predicate
        Predicate<User> predicate = new Predicate<User>()
        {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(User candidate)
            {
                return true;
            }
        };

        // Query the database and get the first result
        List<User> users = getContainer().query(predicate);
        return users;
    }

    /**
     * handle HTTP GET requests.
     */
    @Override
    public Representation getRepresentation(Variant variant)
    {
        DomRepresentation rep = null;
        if (variant.getMediaType().equals(MediaType.TEXT_XML))
        {
            try
            {
                rep = new DomRepresentation(MediaType.TEXT_XML);
                Document d = rep.getDocument();

                Element eltRoot = d.createElement("users");
                d.appendChild(eltRoot);
                for (User user : getUsers())
                {
                    user.fillNodes(d, eltRoot);
                }

                d.normalizeDocument();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return rep;
    }

    @Override
    public boolean allowDelete()
    {
        return false;
    }

    @Override
    public boolean allowPut()
    {
        return false;
    }

    @Override
    public boolean allowPost()
    {
        return true;
    }

    /**
     * Handle HTTP POST. Create a new user resource.
     */
    @Override
    public void post(Representation entity)
    {
        if (entity.getMediaType().equals(MediaType.APPLICATION_WWW_FORM, true))
        {
            // Parse the entity as a web form
            Form form = new Form(entity);

            // create a new User object
            User user = new User();
            user.setUserName(form.getFirstValue("user[name]"));
            user.setHost(form.getFirstValue("user[host]"));
            user.setPort(Integer.parseInt(form.getFirstValue("user[port]")));
            user.setStatus(form.getFirstValue("user[status]").equals("available"));
            getResponse().setStatus(Status.SUCCESS_CREATED);

            // commit the changes.
            getContainer().set(user);
            getContainer().commit();
        }
        else
        {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        }
    }
}
