/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright (c) Ericsson AB, 2004-2007. All rights reserved.
 */
package com.ericsson.ssa.sip;

import com.ericsson.ssa.sip.PathNode.Type;

import java.io.IOException;
import java.io.Serializable;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Servlet;
import javax.servlet.ServletException;


/**
 * Common superclass to ProxyInterface implementations that holds common state
 * and common helper methods.
 *
 * Subclasses implements the dispatch()-methods.
 *
 *
 * @author qmaghes
 *
 */
public abstract class AbstractProxyImpl implements ProxyInterface, Serializable {
    static final Logger _log = (Logger) Logger.getLogger("SipContainer");
    boolean _isAddToPath = false;
    boolean _isRecordRoute = false;
    boolean _isRecurse = true;
    boolean _isParallel = true;
    String _sipApplicationSessionName = null;

    public AbstractProxyImpl(String applicationSessionName) {
        this._sipApplicationSessionName = applicationSessionName;
    }

    /**
     * For deserialization only
     *
     */
    public AbstractProxyImpl() {
    }

    /**
     * Get a confirmed version of this object.
     *
     */
    public final ConfirmedProxyImpl asConfirmed() {
        //      FIXME uncomment for performance reason once DialogFragmentManager does register 180 anymore. 
        //       // If it already is confirmed, return itself.
        //    	if(this instanceof ConfirmedProxyImpl){
        //    		return (ConfirmedProxyImpl)this;
        //    	}
        ConfirmedProxyImpl confirmedProxyImpl = new ConfirmedProxyImpl(_sipApplicationSessionName);
        confirmedProxyImpl._isAddToPath = this._isAddToPath;
        confirmedProxyImpl._isRecordRoute = this._isRecordRoute;
        confirmedProxyImpl._isRecurse = this._isRecurse;
        confirmedProxyImpl._isParallel = this._isParallel;

        return confirmedProxyImpl;
    }

    /*
     * Application session name attribute. Needed for servlet lookup.
     */
    public final String getApplicationSessionName() {
        return _sipApplicationSessionName;
    }

    public final boolean getRecurse() {
        return _isRecurse;
    }

    public final void setRecurse(boolean recurse) {
        _isRecurse = recurse;
    }

    public final boolean getAddToPath() {
        return _isAddToPath;
    }

    public final void setAddToPath(boolean addToPath) {
        _isAddToPath = addToPath;
    }

    public final boolean getRecordRoute() {
        return _isRecordRoute;
    }

    public final void setRecordRoute(boolean recordRoute) {
        _isRecordRoute = recordRoute;
    }

    public final boolean getParallel() {
        return _isParallel;
    }

    public final void setParallel(boolean parallel) {
        _isParallel = parallel;
    }

    public final boolean getStateful() {
        return true;
    }

    @Deprecated
    public void setStateful(boolean stateful) {
    }

    /**
     * Helper to fetch servlet instance.
     *
     * @param handler
     * @return
     */
    public Servlet getServlet(String handler) {
        return SipFactoryImpl.getInstance().getServiceHandler()
                             .getHandler(getApplicationSessionName(), handler);
    }

    /**
     * Helper to set session.
     *
     * @param req
     * @param pc
     * @throws IOException
     * @throws ServletException
     */
    protected void setDerivedOrOriginalSession(SipServletRequestImpl req,
        ProxyContext pc) throws IOException, ServletException {
        // dialog creational NOTIFY
        if (req.getMethod().equals("NOTIFY")) {
            // state Record Route in request to inform
            // that a RecordRoute header must be added
            req.indicateRecordRoute();

            // if the context has a session with same to tag as the dialog, use
            // it...
            if (!pc.getSipSession().hasNoToTag() &&
                    (req.getDialog().getToTag() != null) &&
                    req.getDialog().getToTag()
                           .equals(pc.getSipSession().getToTag())) {
                req.setSession(pc.getSipSession());
            } else {
                // ...otherwise fetch or create one
                DialogFragment df = req.getDialog();

                // lets update to-tag of dialog...
                SipSessionBase s = pc.getSipSession()
                                     .getOriginalOrDerivedSessionAndRegisterDialog(req,
                        df);

                if (s.isDerived()) {
                    // lets set the session cuz it is a derived session
                    req.setSession(s);
                    pc.setSipSession(s);
                }
            }
        } else {
            // the response should already have created
            // the dialog for all other methods...
            req.setSession(pc.getSipSession());
        }
    }

    /**
     * private helper
     *
     * @param resp
     */
    private void dispatchAndClone(SipServletResponseImpl resp) {
        // the request need to be cloned
        SipServletResponseImpl clone = (SipServletResponseImpl) resp.clone();

        // if there is a transaction request, added it to the response...
        SipServletRequestImpl req = resp.getRequestImpl().getTransactionRequest();

        if (req != null) {
            clone.setRequest(req);
            clone.setSession(req.getSessionImpl());
        }

        clone.popDispatcher().dispatch(clone);
    }

    /**
     * private helper
     *
     * @param resp
     * @param pc
     * @throws IOException
     * @throws ServletException
     */
    protected void assignSession(SipServletResponseImpl resp, ProxyContext pc)
        throws IOException, ServletException {
        if (resp.getStatus() != 100) {
            // if the context has a session with same to tag as the dialog, use
            // it...
            if (!pc.getSipSession().hasNoToTag() &&
                    (resp.getDialog().getToTag() != null) &&
                    resp.getDialog().getToTag()
                            .equals(pc.getSipSession().getToTag())) {
                resp.setSession(pc.getSipSession());
            } else {
                // ...otherwise fetch or create one
                DialogFragment df = resp.getDialog();

                // lets update to-tag of dialog...
                SipSessionBase s = resp.getSessionImpl()
                                       .getOriginalOrDerivedSessionAndRegisterDialog(resp,
                        df);

                if (s.isDerived()) {
                    // lets set the session cuz it is a derived session
                    resp.setSession(s);
                }

                pc.setSipSession(s);
            }
        }
    }

    /**
     *
     * common helper
     *
     * @param resp
     * @param pc
     */
    protected void invokeServletAndForward(SipServletResponseImpl resp,
        ProxyContext pc) {
        try {
            assignSession(resp, pc);

            if (resp.getRequestImpl().getSupervised()) {
                // if supervised is enabled invoke the servlet
                invokeServlet(resp);
                dispatchAndClone(resp);
            } else {
                resp.popDispatcher().dispatch(resp);
            }
        } catch (Exception e) {
            // problem in servlet, lets drop response
            if (_log.isLoggable(Level.INFO)) {
                _log.log(Level.INFO, "Problem in servlet.", e);
            }
        }
    }

    /**
     * common helper
     *
     * @param resp
     * @throws IOException
     * @throws ServletException
     */
    protected void invokeServlet(SipServletResponseImpl resp)
        throws IOException, ServletException {
        if (resp.getStatus() != 100) {
            Servlet s = getServlet(resp.getSessionImpl().getHandler());

            if (s != null) {
                resp.getSessionImpl().updateSipSessionState(resp, Type.Proxy);
                s.service(null, resp);
            } else {
                if (_log.isLoggable(Level.INFO)) {
                    _log.log(Level.INFO,
                        "Could not find servlet name: " +
                        resp.getSessionImpl().getHandler() +
                        " in application: " +
                        resp.getSessionImpl().getApplicationSessionImpl()
                            .getName());
                }
            }
        }
    }
}
