/*
 * 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.
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 */
package org.jvnet.glassfish.comms.clb.core;

import com.sun.grizzly.tcp.Request;
import com.sun.grizzly.tcp.Response;
import java.util.logging.Logger;

import org.apache.catalina.Valve;

import org.jvnet.glassfish.comms.clb.admin.CLBConfigurator;
import org.jvnet.glassfish.comms.clb.proxy.api.Endpoint;
import org.jvnet.glassfish.comms.clb.proxy.http.util.HttpRequest;
import org.jvnet.glassfish.comms.httplayers.HttpLayer;
import org.jvnet.glassfish.comms.util.LogUtil;

import java.util.logging.Level;


/**
 *
 * @author kshitiz
 */
public class HttpLoadBalancingManager extends ControllerInitializer
    implements HttpLayer {
    private static HttpLoadBalancingManager instance = new HttpLoadBalancingManager();
    private static final Logger _logger = LogUtil.CLB_LOGGER.getLogger();

    /** Creates a new instance of HttpLoadBalancingManager */
    private HttpLoadBalancingManager() {
    }

    public static HttpLoadBalancingManager getInstance() {
        return instance;
    }

    public String getInfo() {
        return "HTTP load-balancing valve";
    }

    public boolean invoke(Request request, Response response)
        throws Exception {
        
        HttpRequest httpReq = (HttpRequest) request;                
        String requestUri = httpReq.requestURI().toString();
        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.httpLBM_servicing_request",
                    new Object[]{requestUri});
        
        if (ProxyKeyExtractor.isHttpRequestProxied(httpReq)) {
            if(_logger.isLoggable(Level.FINE))
                _logger.log(Level.FINE,
                        "clb.httpLBM_request_already_proxied",
                        new Object[]{requestUri});
            setLocalEndPoint(httpReq);

            return true;
        }

        /* Case Controller is null
         * The possibility is that initialization is not done - This may happen in case 
         * if converged-load-balancer.xml is corrupt or not present at all
         */
        if (controller == null) {
            /* Only case it can be null is when it is not intialized for load-balancing
             * Cannot handle this request so setting error in response
             */
            _logger.log(Level.SEVERE,
                    "clb.controller_null_returning_error",
                    new Object[]{requestUri});
            setErrorInResponse(response);
            return false;
        }

        String appContextPath = null;
        int index = requestUri.indexOf("/", 1);

        if (index > -1) {
            appContextPath = requestUri.substring(0, index);
        } else {
            appContextPath = requestUri;
        }

        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.app_context_for_request",
                    new Object[]{requestUri, appContextPath});

        RequestGroup reqGroup = controller.getRequestGroup(appContextPath);
        
        //if request group is not found lets fall back to default request group
        if(reqGroup == null){
            if(_logger.isLoggable(Level.FINE))
                _logger.log(Level.FINE,
                        "clb.no_request_group_found",
                        new Object[]{requestUri});
            reqGroup = controller.getDefaultHttpRequestGroup();
        }
            
        if (reqGroup == null) {
            /* No request group found for this request
             * let pass it to the same instance and see if it can handle it
             */
            
            if(_logger.isLoggable(Level.FINE))
                _logger.log(Level.FINE,
                        "clb.locally_service_request",
                        new Object[]{requestUri});
            setLocalEndPoint(httpReq);
            return true;
        }

        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.request_group_found",
                    new Object[]{requestUri});
        reqGroup.serviceRequest(httpReq, (Response) response);

        if (httpReq.getConvergedLoadBalancerEndpoint().isLocal()) {
            if(_logger.isLoggable(Level.FINE))
                _logger.log(Level.FINE,
                        "clb.request_to_be_serviced_by_local_endpoint",
                        new Object[]{requestUri});

            return true;
        } else {
            if(_logger.isLoggable(Level.FINE))
                _logger.log(Level.FINE,
                        "clb.request_to_be_serviced_by_remote_endpoint",
                        new Object[]{requestUri});
            return false;
        }
    }

    private void setLocalEndPoint(final HttpRequest httpReq) {
        httpReq.setConvergedLoadBalancerEndpoint(EndPoint.getLocalEndPoint());
    }

    public Controller createController() {
        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.creating_controller_in_httpLBM");

        Controller newController = super.createController();
        newController.setLBType(CLBConstants.HTTP_CLB);

        return newController;
    }

    private void setErrorInResponse(Response response) {
        response.setStatus(500);
    }
}
