/*
 * 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 java.util.logging.Logger;
import org.jvnet.glassfish.comms.clb.proxy.http.util.HttpRequest;
import org.jvnet.glassfish.comms.util.LogUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;


/**
 * Router implementation for round-robin loadbalancing policy
 * @author kshitiz
 */
public class RoundRobinRouter implements Router {
    private static final Logger _logger = LogUtil.CLB_LOGGER.getLogger();

    /* Clusters to which this router can route requests */
    private List<ServerCluster> clusters;

    /* List holding all the available server instances. This include healthy/unhealthy,
     * enabled/disabled instances */
    private ArrayList<ServerInstance> completeInstanceList;

    /* List holding only healthy and enabled instances */
    private ArrayList<ServerInstance> activeInstanceList;

    /* Flag to decide, whether to route to only active instances */
    private boolean activeRouting;

    /* index of instance which will service the request */
    private int index;

    /* controller with which this request group is associated */
    protected Controller controller;

    /* lock to be used when modifying the active list*/
    private Object lock;

    /** Creates a new instance of RoundRobinRouter */
    public RoundRobinRouter(List<ServerCluster> clusters, boolean activeRouting) {
        this.clusters = clusters;
        this.activeRouting = activeRouting;
        lock = new Object();
    }

    public boolean initialize() {
        activeInstanceList = new ArrayList<ServerInstance>();
        completeInstanceList = new ArrayList<ServerInstance>();

        for (ServerCluster cluster : clusters) {
            Collection<ServerInstance> instances = cluster.getAllInstances();
            completeInstanceList.addAll(instances);

            for (ServerInstance instance : instances) {
                instance.addRouter(this);

                if (instance.isEnabled() && instance.isHealthy()) {
                    if(_logger.isLoggable(Level.FINE))
                        _logger.log(Level.FINE,
                                "clb.adding_instance_to_active_list",
                                new Object[]{instance.getName()});
                    addToActiveList(instance);
                } else {
                    if(_logger.isLoggable(Level.FINE))
                        _logger.log(Level.FINE,
                                "clb.not_adding_instance_to_active_list",
                                new Object[]{instance.getName(), instance.isEnabled(),
                                instance.isHealthy()});
                }
            }
        }

        return true;
    }

    public boolean reinitialize(ServerInstance instance) {
        if (instance.isEnabled() && instance.isHealthy()) {
            return addToActiveList(instance);
        }

        return removeFromActiveList(instance);
    }

    public ServerInstance selectInstance(HttpRequest req) {
        return getActiveInstance();
    }

    protected ServerInstance getActiveInstance() {
        synchronized (lock) {
            if(_logger.isLoggable(Level.FINE))
                _logger.log(Level.FINE,
                        "clb.active_list_size",
                        new Object[]{activeInstanceList.size()});
            index = (index + 1) % activeInstanceList.size();
            if(_logger.isLoggable(Level.FINE))
                _logger.log(Level.FINE,
                        "clb.index_selected",
                        new Object[]{index});

            return activeInstanceList.get(index);
        }
    }

    public void handleEnableEvent(ServerInstance instance) {
        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.handling_enable_event",
                    new Object[]{instance.getName()});
        addToActiveList(instance);
    }

    public void handleDisableEvent(ServerInstance instance) {
        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.handling_disable_event",
                    new Object[]{instance.getName()});
        removeFromActiveList(instance);
    }

    public void handleRecoveryEvent(ServerInstance instance) {
        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.handling_recovery_event",
                    new Object[]{instance.getName()});
        addToActiveList(instance);
    }

    public void handleFailureEvent(ServerInstance instance) {
        if(_logger.isLoggable(Level.FINE))
            _logger.log(Level.FINE,
                    "clb.handling_failure_event",
                    new Object[]{instance.getName()});
        removeFromActiveList(instance);
    }

    private boolean addToActiveList(final ServerInstance instance) {
        synchronized (lock) {
            if(!activeInstanceList.contains(instance))
                return activeInstanceList.add(instance);
        }
        return false;
    }
    
    private boolean removeFromActiveList(final ServerInstance instance) {
        synchronized (lock) {
            if(activeInstanceList.contains(instance))
                return activeInstanceList.remove(instance);
        }
        return false;
    }
    
    public ServerInstance selectInstance(ConsistentHashRequest req) {
        // Not relevant for RR
        throw new UnsupportedOperationException(
            "Not applicable for Round-Robin");
    }

    public void setController(Controller controller) {
        this.controller = controller;
    }
}
