/*
 * Copyright (C) 2010 Teleal GmbH, Switzerland
 *
 * This program 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 3 of
 * the License, or (at your option) any later version.
 *
 * This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.teleal.cling.transport;

import org.teleal.cling.UpnpServiceConfiguration;
import org.teleal.cling.model.NetworkAddress;
import org.teleal.cling.model.message.IncomingDatagramMessage;
import org.teleal.cling.model.message.OutgoingDatagramMessage;
import org.teleal.cling.model.message.StreamRequestMessage;
import org.teleal.cling.model.message.StreamResponseMessage;
import org.teleal.cling.protocol.ProtocolFactory;
import org.teleal.cling.transport.spi.InitializationException;
import org.teleal.cling.transport.spi.NetworkAddressFactory;
import org.teleal.cling.transport.spi.UpnpStream;
import org.teleal.common.util.Exceptions;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/**
 * Default implementation of switchable network message router.
 * <p>
 * This implementation is actually wrapping a regular
 * {@link org.teleal.cling.transport.RouterImpl}, making it on/off
 * switchable.
 * </p>
 * <p>
 * If the router can't be enabled (e.g. an exception occurs during
 * socket binding), a warning log message will be printed. You can customize this behavior by
 * overriding {@link #handleStartFailure(org.teleal.cling.transport.spi.InitializationException)}.
 * </p>
 *
 * @author Christian Bauer
 */
public class SwitchableRouterImpl implements SwitchableRouter {

    final private static Logger log = Logger.getLogger(Router.class.getName());

    final private UpnpServiceConfiguration configuration;
    final private ProtocolFactory protocolFactory;
    private Router router;

    public SwitchableRouterImpl(UpnpServiceConfiguration configuration, ProtocolFactory protocolFactory) {
        this.configuration = configuration;
        this.protocolFactory = protocolFactory;
    }

    public UpnpServiceConfiguration getConfiguration() {
        return configuration;
    }

    public ProtocolFactory getProtocolFactory() {
        return protocolFactory;
    }

    synchronized public boolean isEnabled() {
        return router != null;
    }


    synchronized public boolean enable() {
        if (router == null) {
            try {
                log.fine("Enabling network transport router");
                router = new RouterImpl(getConfiguration(), getProtocolFactory());
                return true;
            } catch (InitializationException ex) {
                handleStartFailure(ex);
            }
        }
        return false;
    }

    synchronized public void handleStartFailure(InitializationException ex) {
        log.severe("Unable to initialize network router: " + ex);
        log.severe("Cause: " + Exceptions.unwrap(ex));
    }

    synchronized public boolean disable() {
        if (router != null) {
            log.fine("Disabling network transport router");
            shutdown();
            router = null;
            return true;
        }
        return false;
    }

    synchronized public NetworkAddressFactory getNetworkAddressFactory() {
        if (router != null) return router.getNetworkAddressFactory();
        return new NetworkAddressFactory() {
            public InetAddress getMulticastGroup() {
                return null;
            }

            public int getMulticastPort() {
                return 0;
            }

            public int getStreamListenPort() {
                return 0;
            }

            public NetworkInterface[] getNetworkInterfaces() {
                return new NetworkInterface[0];
            }

            public InetAddress[] getBindAddresses() {
                return new InetAddress[0];
            }

            public byte[] getHardwareAddress(InetAddress inetAddress) {
                return new byte[0];
            }

            public InetAddress getBroadcastAddress(InetAddress inetAddress) {
                return null;
            }

            public InetAddress getLocalAddress(NetworkInterface networkInterface,
                                               boolean isIPv6,
                                               InetAddress remoteAddress)
                    throws IllegalStateException {
                return null;
            }
        };
    }

    synchronized public List<NetworkAddress> getActiveStreamServers(InetAddress preferredAddress) {
        return router != null ? router.getActiveStreamServers(preferredAddress) : Collections.EMPTY_LIST;
    }

    synchronized public void shutdown() {
        if (router != null) router.shutdown();
    }

    synchronized public void received(IncomingDatagramMessage msg) {
        if (router != null) router.received(msg);
    }

    synchronized public void received(UpnpStream stream) {
        if (router != null) router.received(stream);
    }

    synchronized public void send(OutgoingDatagramMessage msg) {
        if (router != null) router.send(msg);
    }

    synchronized public StreamResponseMessage send(StreamRequestMessage msg) {
        if (router != null) return router.send(msg);
        return null;
    }

    synchronized public void broadcast(byte[] bytes) {
        if (router != null) router.broadcast(bytes);
    }
}
