/**
 * 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;

import org.apache.activeblaze.impl.network.Network;
import org.apache.activeblaze.impl.network.NetworkFactory;
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.util.IdGenerator;
import org.apache.activeblaze.util.PropertyUtil;
import org.apache.activeblaze.wire.Buffer;
import org.apache.activeblaze.wire.Packet;

import java.net.URI;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p/>
 * A <CODE>BlazeChannel</CODE> handles all client communication, either unicast,
 * broadcast or multicast with other peers in the Blaze network
 */
public class BlazeChannelImpl extends DefaultChainedProcessor implements BlazeChannel, ExceptionListener {
    protected List<SubscriptionHolder> topicMessageListeners = new CopyOnWriteArrayList<SubscriptionHolder>();
    protected final IdGenerator idGenerator = new IdGenerator();
    protected Buffer producerId;
    protected Processor broadcast;
    protected BlazeConfiguration configuration = new BlazeConfiguration();
    private String id;

    /**
     * Constructor
     */
    protected BlazeChannelImpl() {
        this.id = this.idGenerator.generateId();
        this.producerId = new Buffer(this.id);
    }

    /**
     * @return the id
     * @see org.apache.activeblaze.BlazeChannel#getId()
     */
    public String getId() {
        return this.id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return getId();
    }

    /**
     * @see org.apache.activeblaze.BlazeChannel#addBlazeTopicMessageListener(java.lang.String,
     *      org.apache.activeblaze.BlazeMessageListener)
     */
    public void addBlazeTopicMessageListener(String destination, BlazeMessageListener l) throws Exception {
        SubscriptionHolder key = new SubscriptionHolder(destination, true, l);
        this.topicMessageListeners.add(key);
    }

    /**
     * @see org.apache.activeblaze.BlazeChannel#addBlazeTopicMessageListener(java.lang.String,
     *      org.apache.activeblaze.BlazeMessageListener)
     */
    public void addBlazeTopicMessageListener(Subscription subscription, BlazeMessageListener l) throws Exception {
        SubscriptionHolder key = new SubscriptionHolder(subscription, l);
        this.topicMessageListeners.add(key);
    }

    /**
     * @param destination
     * @param l
     * @throws Exception
     */
    public void removeBlazeTopicMessageListener(String destination, BlazeMessageListener l) throws Exception {
        SubscriptionHolder key = new SubscriptionHolder(destination, true, l);
        this.topicMessageListeners.remove(key);
    }

    /**
     * @param subs
     * @param l
     * @throws Exception
     */
    public void removeBlazeTopicMessageListener(Subscription subs, BlazeMessageListener l) throws Exception {
        SubscriptionHolder key = new SubscriptionHolder(subs, l);
        this.topicMessageListeners.remove(key);
    }

    public void doInit() throws Exception {
        super.doInit();
        String broadcastURIStr = getConfiguration().getBroadcastURI();
        broadcastURIStr = PropertyUtil.addPropertiesToURIFromBean(broadcastURIStr, getConfiguration());
        URI broadcastURI = new URI(broadcastURIStr);
        URI managementURI = null;
        String managementURIStr = getConfiguration().getManagementURI();
        if (managementURIStr != null && managementURIStr.length() > 0) {
            managementURI = new URI(getConfiguration().getManagementURI());
        }
        Network transport = NetworkFactory.get(broadcastURI, managementURI, getConfiguration().getReliableBroadcast());
        transport.setName(getName());
        this.broadcast = configureProcess(transport);
        this.broadcast.init();
    }

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

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

    public void doShutDown() throws Exception {
        super.doShutDown();
        Processor p = this.broadcast;
        if (p != null) {
            p.shutDown();
        }
    }

    public void doStart() throws Exception {
        super.doStart();
        this.broadcast.start();
    }

    public void doStop() throws Exception {
        super.doStop();
        this.broadcast.stop();
    }

    public void broadcast(String destination, BlazeMessage msg) throws Exception {
        broadcast(new Destination(destination, true), msg);
    }

    public void broadcast(Destination destination, BlazeMessage msg) throws Exception {
        msg.setDestination(destination);
        preProcessMessage(destination, msg);
        this.broadcast.downStream(msg);
    }

    public void upStream(Packet packet) throws Exception {
        processPacket(packet);
    }

    protected void preProcessMessage(Destination destination, BlazeMessage message) {
        message.setDestination(destination);
        message.setProducerId(this.id);
        if (message.getId() == null) {
            message.setId(this.idGenerator.generateId());
        }
    }

    protected void processPacket(Packet packet) throws Exception {
        if (packet instanceof BlazeMessage) {
            dispatch((BlazeMessage) packet);
        }
    }

    public BlazeConfiguration getConfiguration() {
        return this.configuration;
    }

    /**
     * Set the configuration
     */
    public void setConfiguration(BlazeConfiguration configuration) {
        this.configuration = configuration;
    }

    /**
     * @see org.apache.activeblaze.ExceptionListener#onException(java.lang.Exception)
     */
    public void onException(Exception ex) {
        doFireException(ex);
    }

    protected final void dispatch(BlazeMessage message) throws Exception {
        if (message != null) {
            if (message.getDestination() != null) {
                Buffer destination = message.getDestination().getName();
                for (SubscriptionHolder entry : this.topicMessageListeners) {
                    if (entry.getSubscription().matches(destination)) {
                        entry.getListener().onMessage(message);
                    }
                }
            }
        }
    }
}
