/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activeblaze.group;

import org.apache.activeblaze.*;
import org.apache.activeblaze.impl.processor.ChainedProcessor;
import org.apache.activeblaze.impl.processor.DefaultChainedProcessor;
import org.apache.activeblaze.impl.reliable.ReliableFactory;
import org.apache.activeblaze.impl.transport.BaseTransport;
import org.apache.activeblaze.impl.transport.TransportFactory;
import org.apache.activeblaze.util.AsyncGroupRequest;
import org.apache.activeblaze.util.LRUCache;
import org.apache.activeblaze.util.PropertyUtil;
import org.apache.activeblaze.util.SendRequest;
import org.apache.activeblaze.wire.Buffer;
import org.apache.activeblaze.wire.MemberImpl;
import org.apache.activeblaze.wire.Packet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p/>
 * A <CODE>BlazeGroupChannel</CODE> enables peer-based point to point
 * communication
 */
public class BlazeGroupChannelImpl extends BlazeChannelImpl implements BlazeGroupChannel {
    private static final Log LOG = LogFactory.getLog(BlazeGroupChannelImpl.class);
    private String name;
    protected Processor unicast;
    private MemberImpl local;
    private BlazeMessageListener inboxListener;
    protected Map<String, SendRequest> messageRequests = new LRUCache<String, SendRequest>(10000);
    private final List<SubscriptionHolder> queueMessageListeners = new CopyOnWriteArrayList<SubscriptionHolder>();
    private Group group;
    protected Buffer inboxAddress;
    protected int inBoxPort;
    protected final Object localMutex = new Object();

    /**
     * Constructor
     */
    protected BlazeGroupChannelImpl(String name) {
        super();
        this.name = name;
    }

    /**
     * @see org.apache.activeblaze.Service#init()
     */
    public void doInit() throws Exception {
        super.doInit();
        String unicastURIStr = getConfiguration().getUnicastURI();
        unicastURIStr = PropertyUtil.addPropertiesToURIFromBean(unicastURIStr, getConfiguration());
        URI unicastURI = new URI(unicastURIStr);
        BaseTransport transport = TransportFactory.get(unicastURI);
        transport.setName(getId() + "-Unicast");
        this.unicast = configureProcess(transport, getConfiguration().getReliableUnicast());
        this.unicast.init();
        // if using a port of zero - the port will be assigned automatically,
        // so need to get the potentially new value
        unicastURI = transport.getLocalURI();
        InetSocketAddress addr = new InetSocketAddress(unicastURI.getHost(), unicastURI.getPort());
        this.inboxAddress = new Buffer(addr.getAddress().getAddress());
        this.inBoxPort = addr.getPort();
        this.local = createLocal(unicastURI);
        this.group = createGroup();
    }

    protected final ChainedProcessor configureProcess(ChainedProcessor transport, String reliability) throws Exception {
        int maxPacketSize = getConfiguration().getMaxPacketSize();
        ChainedProcessor result = getReliability(reliability);
        result.setPrev(this);
        result.setExceptionListener(this);
        result.setMaxPacketSize(maxPacketSize);
        result.setEnd(transport);
        return result;
    }

    protected ChainedProcessor getReliability(String reliability) throws Exception {
        DefaultChainedProcessor reliable = ReliableFactory.get(reliability);
        return reliable;
    }

    protected MemberImpl createLocal(URI uri) throws Exception {
        return new MemberImpl(getId(), getName(), 0, 0, uri);
    }

    protected Group createGroup() {
        return new Group(this);
    }

    /**
     * @see org.apache.activeblaze.Service#shutDown()
     */
    public void doShutDown() throws Exception {
        super.doShutDown();
        if (this.group != null) {
            this.group.shutDown();
        }
        if (this.unicast != null) {
            this.unicast.shutDown();
        }
    }

    /**
     * @see org.apache.activeblaze.Service#start()
     */
    public void doStart() throws Exception {
        super.doStart();
        this.unicast.start();
        this.group.start();
    }

    /**
     * @see org.apache.activeblaze.Service#stop()
     */
    public void doStop() throws Exception {
        super.doStop();
        this.group.stop();
        this.unicast.stop();
    }

    /**
     * @return the name
     */
    public String getName() {
        synchronized (this.localMutex) {
            return this.name;
        }
    }

    /**
     * set the name
     *
     * @see org.apache.activeblaze.group.BlazeGroupChannel#setName(java.lang.String)
     */
    public void setName(String name) {
        synchronized (this.localMutex) {
            this.name = name;
            if (this.local != null) {
                this.local.setName(name);
            }
        }
    }

    /**
     * @return the inboxListener
     */
    public BlazeMessageListener getInboxListener() {
        return this.inboxListener;
    }

    /**
     * @param inboxListener the inboxListener to set
     */
    public void setInboxListener(BlazeMessageListener inboxListener) {
        this.inboxListener = inboxListener;
    }

    /**
     * @return this channel's configuration
     * @see org.apache.activeblaze.group.BlazeGroupChannel#getConfiguration()
     */
    public BlazeGroupConfiguration getConfiguration() {
        return (BlazeGroupConfiguration) this.configuration;
    }

    /**
     * @return the member for this channel
     * @see org.apache.activeblaze.group.BlazeGroupChannel#getLocalMember()
     */
    public MemberImpl getLocalMember() {
        synchronized (this.localMutex) {
            return this.local;
        }
    }

    protected void setLocalMember(MemberImpl local) {
        synchronized (this.localMutex) {
            this.local = local;
        }
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#addMemberChangedListener(org.apache.activeblaze.group.MemberChangedListener)
     */
    public void addMemberChangedListener(MemberChangedListener l) throws Exception {
        init();
        this.group.addMemberChangedListener(l);
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#removeMemberChangedListener(org.apache.activeblaze.group.MemberChangedListener)
     */
    public void removeMemberChangedListener(MemberChangedListener l) throws Exception {
        init();
        this.group.removeMemberChangedListener(l);
    }

    /**
     * @return the Member
     * @see org.apache.activeblaze.group.BlazeGroupChannel#getMemberById(java.lang.String)
     */
    public Member getMemberById(String id) throws Exception {
        init();
        return this.group.getMemberById(id);
    }

    /**
     * @return the Member
     * @see org.apache.activeblaze.group.BlazeGroupChannel#getMemberByName(java.lang.String)
     */
    public Member getMemberByName(String memberName) throws Exception {
        init();
        return this.group.getMemberByName(memberName);
    }

    /**
     * Will wait for a member to advertise itself if not available
     *
     * @return the member or null
     */
    public Member getAndWaitForMemberByName(String memberName, int timeout) throws Exception {
        init();
        return this.group.getAndWaitForMemberByName(memberName, timeout);
    }

    /**
     * @return the members
     * @see org.apache.activeblaze.group.BlazeGroupChannel#getMembers()
     */
    public Set<Member> getMembers() throws Exception {
        init();
        return this.group.getMembers();
    }

    /**
     * Send a message to a member of the group - in a round-robin fashion
     *
     * @see org.apache.activeblaze.group.BlazeGroupChannel#send(java.lang.String,
     *      org.apache.activeblaze.BlazeMessage)
     */
    public void send(String destination, BlazeMessage message) throws Exception {
        send(new Destination(new Buffer(destination), false), message);
    }

    /**
     * Send a message to a member of the group - in a round-robin fashion
     *
     * @see org.apache.activeblaze.group.BlazeGroupChannel#send(java.lang.String,
     *      org.apache.activeblaze.BlazeMessage)
     */
    public void send(Destination destination, BlazeMessage message) throws Exception {
        while (true) {
            MemberImpl member = getQueueDestination(destination.getName());
            if (member != null) {
                try {
                    send(member, destination.getName(), message);
                    return;
                } catch (BlazeNoRouteException e) {
                    LOG.debug("No response - resending to another client", e);
                }
            } else {
                return;
            }
        }
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#send(org.apache.activeblaze.group.Member,
     *      org.apache.activeblaze.BlazeMessage)
     */
    public void send(Member member, BlazeMessage message) throws Exception {
        send((MemberImpl) member, member.getInBoxDestination(), message);
    }

    /**
     * @return the response
     * @see org.apache.activeblaze.group.BlazeGroupChannel#sendRequest(org.apache.activeblaze.group.Member,
     *      org.apache.activeblaze.BlazeMessage)
     */
    public BlazeMessage sendRequest(Member member, BlazeMessage message) throws Exception {
        return sendRequest(member, message, 0);
    }

    /**
     * @return the response
     * @see org.apache.activeblaze.group.BlazeGroupChannel#sendRequest(org.apache.activeblaze.group.Member,
     *      org.apache.activeblaze.BlazeMessage, int)
     */
    public BlazeMessage sendRequest(Member member, BlazeMessage message, int timeout) throws Exception {
        return sendRequest((MemberImpl) member, member.getInBoxDestination(), message, timeout);
    }

    /**
     * @return the response
     * @see org.apache.activeblaze.group.BlazeGroupChannel#sendRequest(java.lang.String,
     *      org.apache.activeblaze.BlazeMessage)
     */
    public BlazeMessage sendRequest(String destination, BlazeMessage message) throws Exception {
        return sendRequest(new Destination(destination, false), message, 0);
    }

    /**
     * @return the response
     * @see org.apache.activeblaze.group.BlazeGroupChannel#sendRequest(java.lang.String,
     *      org.apache.activeblaze.BlazeMessage)
     */
    public BlazeMessage sendRequest(Destination destination, BlazeMessage message) throws Exception {
        return sendRequest(destination, message, 0);
    }

    /**
     * @return the request
     * @see org.apache.activeblaze.group.BlazeGroupChannel#sendRequest(java.lang.String,
     *      org.apache.activeblaze.BlazeMessage, int)
     */
    public BlazeMessage sendRequest(String destination, BlazeMessage message, int timeout) throws Exception {
        return sendRequest(new Destination(destination, false), message, timeout);
    }

    /**
     * @return the response
     * @see org.apache.activeblaze.group.BlazeGroupChannel#sendRequest(java.lang.String,
     *      org.apache.activeblaze.BlazeMessage, int)
     */
    public BlazeMessage sendRequest(Destination destination, BlazeMessage message, int timeout) throws Exception {
        Buffer key = destination.getName();
        long deadline = 0;
        long waitTime = timeout;
        if (timeout > 0) {
            deadline = System.currentTimeMillis() + timeout;
        }
        while (!isStopped() && (timeout == 0 || waitTime > 0)) {
            MemberImpl member = getQueueDestination(key);
            if (member != null) {
                try {
                    BlazeMessage result = sendRequest(member, destination, message, (int) waitTime);
                    if (result != null) {
                        return result;
                    }
                } catch (BlazeNoRouteException e) {
                } finally {
                    if (timeout > 0) {
                        waitTime = (int) Math.max(deadline - System.currentTimeMillis(), 0);
                    }
                }
            } else {
                this.group.waitForNewMember((int) waitTime);
            }
        }
        return null;
    }

    /**
     * send Request
     *
     * @return the response
     */
    public BlazeMessage sendRequest(MemberImpl member, String destinationName, BlazeMessage message, int timeout)
            throws Exception {
        return sendRequest(member, new Destination(destinationName, false), message, timeout);
    }

    /**
     * send Request
     *
     * @return the response
     */
    public BlazeMessage sendRequest(MemberImpl member, Destination dest, BlazeMessage message, int timeout)
            throws Exception {
        BlazeMessage result = null;
        if (member != null) {
            SendRequest request = new SendRequest();
            preProcessMessage(((MemberImpl) member).getAddress(), dest, message);
            synchronized (this.messageRequests) {
                this.messageRequests.put(message.getId(), request);
            }
            this.unicast.downStream(message);
            result = (BlazeMessage) request.get(timeout);
        }
        return result;
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#sendReply(org.apache.activeblaze.group.Member,
     *      org.apache.activeblaze.BlazeMessage, java.lang.String)
     */
    public void sendReply(Member to, BlazeMessage response, String correlationId) throws Exception {
        Destination dest = new Destination(to.getInBoxDestination(), false);
        preProcessMessage(((MemberImpl) to).getAddress(), dest, response);
        response.setCorrelationId(correlationId);
        this.unicast.downStream(response);
    }

    protected void send(MemberImpl member, String destinationName, BlazeMessage message) throws Exception {
        send(member, new Buffer(destinationName), message);
    }

    protected void send(MemberImpl member, Buffer destinationName, BlazeMessage message) throws Exception {
        Destination dest = new Destination(destinationName, false);
        preProcessMessage(member.getAddress(), dest, message);
        this.unicast.downStream(message);
    }

    protected void preProcessMessage(InetSocketAddress to, Destination destination, BlazeMessage message) {
        preProcessMessage(destination, message);
        message.setTo(to);
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#addBlazeQueueMessageListener(java.lang.String,
     *      BlazeMessageListener)
     */
    public void addBlazeQueueMessageListener(String destination, BlazeMessageListener l) throws Exception {
        init();
        SubscriptionHolder key = new SubscriptionHolder(destination, false, l);
        this.queueMessageListeners.add(key);
        buildLocal();
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#addBlazeQueueMessageListener(java.lang.String,
     *      BlazeMessageListener)
     */
    public void addBlazeQueueMessageListener(Subscription subscription, BlazeMessageListener l) throws Exception {
        init();
        SubscriptionHolder key = new SubscriptionHolder(subscription, l);
        this.queueMessageListeners.add(key);
        buildLocal();
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#removeBlazeQueueMessageListener(java.lang.String, BlazeMessageListener)
     */
    public void removeBlazeQueueMessageListener(String destination, BlazeMessageListener l) throws Exception {
        init();
        SubscriptionHolder key = new SubscriptionHolder(destination, false, l);
        this.queueMessageListeners.remove(key);
        buildLocal();
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#removeBlazeQueueMessageListener(java.lang.String, BlazeMessageListener)
     */
    public void removeBlazeQueueMessageListener(Subscription subscription, BlazeMessageListener l) throws Exception {
        init();
        SubscriptionHolder key = new SubscriptionHolder(subscription, l);
        this.queueMessageListeners.remove(key);
        buildLocal();
    }

    /**
     * @see org.apache.activeblaze.BlazeChannel#addBlazeTopicMessageListener(java.lang.String,
     *      org.apache.activeblaze.BlazeMessageListener)
     */
    public void addBlazeTopicMessageListener(String destination, BlazeMessageListener l) throws Exception {
        init();
        super.addBlazeTopicMessageListener(destination, l);
        buildLocal();
    }

    /**
     * @see org.apache.activeblaze.BlazeChannel#removeBlazeTopicMessageListener(java.lang.String, BlazeMessageListener)
     */
    public void removeBlazeTopicMessageListener(String destination, BlazeMessageListener l) throws Exception {
        init();
        super.removeBlazeTopicMessageListener(destination, l);
        buildLocal();
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#addToGroup(java.lang.String)
     */
    public void addToGroup(String groupName) throws Exception {
        init();
        this.local.addToGroup(groupName);
    }

    /**
     * @see org.apache.activeblaze.group.BlazeGroupChannel#removeFromGroup(java.lang.String)
     */
    public void removeFromGroup(String groupName) throws Exception {
        init();
        this.local.removeFromGroup(groupName);
    }

    /**
     * @return the groups
     * @see org.apache.activeblaze.group.BlazeGroupChannel#getGroups()
     */
    public List<String> getGroups() throws Exception {
        init();
        return this.local.getGroups();
    }

    protected void processPacket(Packet packet) throws Exception {
        if (isStarted()) {
            if (!processRequest(packet)) {
                if (packet instanceof BlazeMessage) {
                    doProcessBlazeMessage((BlazeMessage) packet);
                } else if (packet instanceof Member) {
                    doProcessMember((MemberImpl) packet);
                }
            }
        }
    }

    protected boolean processRequest(Packet packet) {
        boolean result = false;
        String correlationId = packet.getCorrelationId();
        if (correlationId != null && correlationId.length() > 0) {
            SendRequest request = null;
            synchronized (this.messageRequests) {
                request = this.messageRequests.remove(correlationId);
            }
            if (request != null) {
                request.put(correlationId, packet);
                result = true;
            }
        }
        return result;
    }

    protected void doProcessBlazeMessage(BlazeMessage message) throws Exception {
        Destination destination = message.getDestination();
        if (destination != null) {
            if (destination.isTopic()) {
                dispatch(message);
            } else {
                if (this.inboxListener != null && this.producerId.equals(destination.getName())) {
                    this.inboxListener.onMessage(message);
                } else {
                    int index = 0;
                    for (SubscriptionHolder entry : this.queueMessageListeners) {
                        if (entry.getSubscription().matches(destination.getName())) {
                            entry.getListener().onMessage(message);
                            this.queueMessageListeners.remove(index);
                            this.queueMessageListeners.add(entry);
                        }
                        index++;
                    }
                }
            }
        }
    }

    protected Group getGroup() {
        return this.group;
    }

    protected BlazeMessage createMessage(String fromId) {
        Member member = this.group.getMemberById(fromId);
        BlazeMessage message = new BlazeGroupMessage(member);
        return message;
    }

    protected final void doProcessMember(MemberImpl member) throws Exception {
        this.group.processMember(member);
    }

    /**
     * @param packet
     * @throws Exception
     */
    public void broadcastManagementMessage(Packet packet) throws Exception {
        this.broadcast.downStreamManagement(packet);
    }

    /**
     * send a message
     */
    public void sendGroupRequest(AsyncGroupRequest asyncRequest, MemberImpl member, Packet packet) throws Exception {
        SendRequest request = new SendRequest();
        asyncRequest.add(packet.getId(), request);
        synchronized (this.messageRequests) {
            this.messageRequests.put(packet.getId(), request);
        }
        packet.setReliable(true);
        packet.setTo(member.getAddress());
        this.unicast.downStream(packet);
    }

    /**
     * broadcast a general message
     */
    public void broadcastManagementMessage(Packet packet, String correlationId) throws Exception {
        packet.setCorrelationId(correlationId);
        packet.setReliable(true);
        this.broadcast.downStreamManagement(packet);
    }

    /**
     * @param to
     * @param packet
     * @throws Exception
     */
    public void sendManagementMessage(InetSocketAddress to, Packet packet) throws Exception {
        packet.setReliable(false);
        packet.setTo(to);
        this.unicast.downStream(packet);
    }

    /**
     * @param to
     * @param packet
     * @param correlationId
     * @throws Exception
     */
    public void sendReply(MemberImpl to, Packet packet, String correlationId) throws Exception {
        packet.setReliable(false);
        packet.setTo(to.getAddress());
        packet.setCorrelationId(correlationId);
        this.unicast.downStream(packet);
    }

    protected MemberImpl getQueueDestination(Buffer destination) {
        // choose a member
        MemberImpl result = null;
        Map<Subscription, List<MemberImpl>> map = this.group.getQueueMap();
        Subscription key = new Subscription(destination, false);
        List<MemberImpl> list = map.get(key);
        if (list == null) {
            // search through wildcard matches
            for (Subscription s : map.keySet()) {
                if (s.matches(destination)) {
                    list = map.get(s);
                    break;
                }
            }
        }
        if (list != null && !list.isEmpty()) {
            result = list.remove(0);
            // round-robin
            list.add(result);
        }
        return result;
    }

    protected void buildLocal() {
        if (isInitialized()) {
            try {
                synchronized (this.localMutex) {
                    MemberImpl result = getLocalMember().clone();
                    result.clearSubscriptions();
                    // add topic destinations
                    for (SubscriptionHolder s : this.topicMessageListeners) {
                        result.addSubscription(s.getSubscription());
                    }
                    // add Queue Destinations
                    for (SubscriptionHolder s : this.queueMessageListeners) {
                        result.addSubscription(s.getSubscription());
                    }
                    this.group.processMemberUpdate(this.local, result);
                    this.group.broadcastHeartBeat(result);
                    this.local = result;
                    this.group.updateLocal(this.local);
                }
            } catch (Exception e) {
                LOG.error("Failed to update local member ", e);
            }
        } else {
            throw new BlazeRuntimeException("Not Initialized");
        }
    }
}
