/*
 * 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.eas.telurl.TelUrlResolver;
import com.ericsson.eas.telurl.TelUrlResolverException;

import com.ericsson.ssa.sip.dns.DnsResolver;

import java.io.IOException;

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

import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.URI;


/**
 * This class is used to wrap around a SIP request to access the URI regardless
 * of URI implementation (SipURI or TelURL), so that equivalent parts that are
 * not specified in the URI interface can be accessed.
 *
 *
 * @author ejoelbi
 * @since 2006-dec-21
 * @reviewed qmigkra 2007-jan-17
 *
 */
public class UriWrapper {
    private static Logger _log = (Logger) Logger.getLogger("SipContainer");
    private static SipFactory sf = SipFactoryImpl.getInstance();
    static TelUrlResolver resolver = (TelUrlResolver) DnsResolver.getInstance();
    private URI transformedUri;
    private SipServletRequest req;
    private boolean hasDoneTransform;

    /**
     * Constructor.
     *
     * @param req
     *           the message containing the URI to be wrapped
     * @throws IllegalArgumentException
     *            if the message cintains an URI that is not a TelURLImpl nor a
     *            SipURI
     */
    public UriWrapper(SipServletRequest req) {
        this.req = req;

        URI uriToBeWrapped = req.getRequestURI();

        if (!(uriToBeWrapped instanceof SipURI ||
                uriToBeWrapped instanceof TelURLImpl)) {
            throw new IllegalArgumentException("The URI class: " +
                uriToBeWrapped.getClass() + " is not supported");
        }
    }

    /**
     * Gets the transformed URI
     *
     * @return the transformed URI
     */
    public URI getTransformedUri() {
        if (!hasDoneTransform) {
            URI uri = req.getRequestURI();
            transformedUri = transformURI(uri);

            if (SipFactoryImpl.TEL_URI_PROTOCOL.equals(uri.getScheme()) &&
                    (transformedUri == null)) {
                transformedUri = uri;
            }

            hasDoneTransform = true;
        }

        return transformedUri;
    }

    /**
     * Transform a URI to a SipURI. If the URI is a TelURL then perform an
     * ENUM lookup of the SipURI.
     *
     * @param uri
     * @return SipURI or null
     */
    private SipURI transformURI(URI uri) {
        SipURI sipUri = null;

        if (_log.isLoggable(Level.FINE)) {
            _log.log(Level.FINE, "transformURI uri: " + uri);
        }

        if (uri.isSipURI()) {
            sipUri = (SipURI) uri;

            String user = sipUri.getParameter("user");

            //           if(_log.isLoggable(Level.FINE))
            //           {
            //              _log.log(Level.FINE, "transformURI user: "+user);
            //           }
            if ((user != null) && user.equals("phone")) {
                //Do the ENUM first
                sipUri = resolve(uri);
            }
        } else if (resolver.isTelephoneNumber(uri)) {
            sipUri = resolve(uri);
        }

        return sipUri;
    }

    /**
     * Resolve a TelURL to the users SipURI
     * @param uri
     * @return
     */
    private SipURI resolve(URI uri) {
        SipURI sipUri = null;

        if (_log.isLoggable(Level.FINE)) {
            _log.log(Level.FINE, "resolve uri: " + uri);
        }

        //      if (uri.isPhoneNumber()) {
        if (resolver.isTelephoneNumber(uri)) {
            try {
                sipUri = resolver.lookupSipURI(uri);

                if (_log.isLoggable(Level.FINE)) {
                    _log.log(Level.FINE, "uri: " + uri);
                    _log.log(Level.FINE, "resolves to: " + sipUri);
                }
            } catch (IOException ioe) {
                if (_log.isLoggable(Level.FINE)) {
                    _log.log(Level.FINE, "failed to resolve: " + ioe);
                }
            } catch (TelUrlResolverException telExc) {
                if (_log.isLoggable(Level.FINE)) {
                    _log.log(Level.FINE,
                        "TelUrlResolverException, failed to resolve: " + uri);
                }
            }
        }

        return sipUri;
    }

    /**
     * Sets the specified parameter of the URI in the request to the specified
     * value.
     *
     * @param name
     *           parameter name
     * @param value
     *           parameter value
     */
    public void setParameter(String name, String value) {
        UriUtil.setParameter(req.getRequestURI(), name, value);
    }

    /**
     * Remove the specified parameter of the URI in the request.
     *
     * @param name
     *           the parameter name
     * @return the value of the removed parameter (or null if parameter does not
     *         exist)
     */
    public String removeParameter(String name) {
        return UriUtil.removeParameter(req.getRequestURI(), name);
    }

    /**
     * Gets the value of the specified parameter of the URI in the request.
     *
     * @param name
     *           parameter name
     */
    public String getParameter(String name) {
        return UriUtil.getParameter(req.getRequestURI(), name);
    }

    @Override
    public String toString() {
        return "Request-URI: " + req.getRequestURI() +
        "; Transformed Request-URI: " + getTransformedUri();
    }
}
