/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.jaxrs.jersey.internal;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.UriBuilder;

import org.osgi.framework.ServiceReference;

/**
 * A {@code PathUtils} is responsible to compute web context path information.
 *
 * @author Guillaume Sauthier
 */
public class PathUtils {

    /**
     * Build the context path of the given Application
     * @param application REST application
     * @param reference OSGi ServiceReference associated to the Application
     * @return a valid context path
     */
    public static String getContextPath(final Application application,
                                        final ServiceReference reference) {

        StringBuilder sb = new StringBuilder();
        String path = (String) reference.getProperty(JerseyApplicationPublisher.CONTEXT_PROPERTY);
        if (path != null) {
            // Use provided path value
            path = cleanupPath(path);
            sb.append(path);
        } else {
            // Compute path value from ServiceReference
            // Notice that if 1 Bundle registers 2 (or more) Applications without
            // specifying a context path, there will be a context name collision.
            sb.append('/')
              .append(reference.getBundle().getSymbolicName())
              .append('/')
              .append(reference.getBundle().getVersion());
        }

        // Respect @ApplicationPath if present
        Class<? extends Application> appClass = application.getClass();
        if (appClass.isAnnotationPresent(ApplicationPath.class)) {
            String applicationPath = appClass.getAnnotation(ApplicationPath.class).value();
            if (applicationPath != null) {
                applicationPath = cleanupPath(applicationPath);
                sb.append(applicationPath);
            }
        }

        // Clean the path using an UriBuilder (for encoding support)
        return UriBuilder.fromPath(sb.toString())
                         .build()
                         .toASCIIString();
    }

    private static String cleanupPath(final String path) {
        String cleaned = path;
        if (path.charAt(0) != '/') {
            // Add a leading '/'
            cleaned = "/" + path;
        }

        if (path.endsWith("/") && (!"/".equals(path))) {
            // Remove trailing '/'
            cleaned = cleaned.substring(0, cleaned.length() - 1);
        }
        
        return cleaned;
    }
}
