/*
 * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.web;

import com.arsdigita.web.Application;
import com.arsdigita.kernel.User;
import com.arsdigita.kernel.security.UserContext;
import com.arsdigita.util.Assert;
import com.arsdigita.util.Record;
import org.apache.log4j.Logger;

/**
 * <p>A session object that provides an environment in which code can
 * execute. The WebContext contains all session-specific variables.
 * One session object is maintained per thread.</p>
 *
 * <p>Accessors of this class may return null.  Developers should take
 * care to trap null return values in their code.</p>
 *
 * @author Rafael Schloming
 * @author Justin Ross
 */
public final class WebContext extends Record {
    public static final String versionId =
        "$Id: //core-platform/dev/src/com/arsdigita/web/WebContext.java#19 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log = Logger.getLogger(WebContext.class);

    private Application m_application = null;
    private URL m_requestURL = null;

    private static String[] s_fields = new String[] {
        "User",
        "Application",
        "RequestURL"
    };

    WebContext() {
        super(WebContext.class, s_log, s_fields);
    }

    final WebContext copy() {
        WebContext result = new WebContext();

        result.m_application = m_application;
        result.m_requestURL = m_requestURL;

        return result;
    }

    final void init(final Application app, final URL requestURL) {
        setApplication(app);
        setRequestURL(requestURL);
    }

    final void clear() {
        m_application = null;
        m_requestURL = null;
    }

    public final User getUser() {
        UserContext context = Web.getUserContext();

        if (context == null || !context.isLoggedIn()) {
            return null;
        } else {
            return context.getUser();
        }
    }

    public final Application getApplication() {
        return m_application;
    }

    final void setApplication(final Application app) {
        m_application = app;

        mutated("Application");
    }

    public final URL getRequestURL() {
        return m_requestURL;
    }

    final void setRequestURL(final URL url) {
        Assert.assertNotNull(url, "URL url");

        m_requestURL = url;

        mutated("RequestURL");
    }
}
