/*
 * 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 Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.teleal.cling.protocol.async;

import org.teleal.cling.UpnpService;
import org.teleal.cling.model.ValidationError;
import org.teleal.cling.model.meta.Phase;
import org.teleal.cling.model.meta.RemoteDevice;
import org.teleal.cling.model.meta.RemoteDeviceIdentity;
import org.teleal.cling.model.ValidationException;
import org.teleal.cling.model.message.IncomingDatagramMessage;
import org.teleal.cling.model.message.UpnpRequest;
import org.teleal.cling.model.message.discovery.IncomingNotificationRequest;
import org.teleal.cling.protocol.ReceivingAsync;
import org.teleal.cling.protocol.RetrieveRemoteDescriptors;

import java.util.logging.Logger;

/**
 * Why does this (control point) protocol implementation ignore anything but root device notification messages?
 * <p/>
 * The UDA 1.0 spec says that if a device comes online, it will send out dozens of advertisement messages.
 * <p/>
 * The general question is: Why would any control point even react to a notification message that is not for a
 * root device? They don't arrive ordered, and what would you do when you receive a service notification
 * before you receive its root device notification. You can't use the service anyway... and once you have
 * the root device notification, go grab the device descriptor and you will find the services. I can only
 * assume that this was specified so that control points may filter the services they can handle in the
 * discovery stage, before descriptors are exchanged. Given that there is dozens of messages being exchanged,
 * I'm not sure what the designers hoped to gain from this. It's certainly very convoluted and they even had
 * to explain how not to flood the network in UDA 1.1.
 * <p/>
 * The UDA 1.0 spec says (in 1.1.2):
 * "... order is unimportant, but refreshing or canceling individual messages is prohibited."
 * <p/>
 * So this looks like we can always treat the life cycle of a 'device' as a composite with all
 * embedded devices and services dependend on that root device. In other words, we don't care if an
 * 'alive' or 'byebye' is announced for an embedded device or a service because as long as the root
 * device doesn't appear or disappear, nothing changes.
 * <p/>
 * To cause further confusion, the following was added to the UDA 1.1 spec (in 1.3):
 * <p/>
 * "If a control point has received at least one 'byebye' message of a root device, embedded device, or
 * service, then the control point can assume that all are no longer available."
 * <p/>
 * Well, this control point doesn't care then, as long as the root device has not been 'bybye'd or expired.
 * <p/>
 * "Only when all original advertisements of a root device, embedded device, and services have
 * expired can a control point assume that they are no longer available."
 * <p/>
 * This could mean that even if we get 'byeby'e for the root device, we still have to assume that its services
 * are available. That clearly makes no sense at all and I think it's just badly worded and relates to the
 * previous sentence wich says "if you don't get byebye's, rely on the expiration timeout". It does not
 * imply that a service or embedded device lives beyond its root device. It actually reinforces that we are
 * free to ignore anything that happens as long as the root device is not gone with 'byebye' or has expired.
 * <p/>
 * Finally, note that all advertisement messages contain a Location header with the URL of the root
 * device descriptor. So theoretically we could take any notification message that comes in, grab the device
 * descriptor, and go off retrieving the really important information. It is however simpler to just do that
 * for root device advertisement messages and ignore everything else.
 */
public class ReceivingNotification extends ReceivingAsync<IncomingNotificationRequest> {

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

    public ReceivingNotification(UpnpService upnpService, IncomingDatagramMessage<UpnpRequest> inputMessage) {
        super(upnpService, new IncomingNotificationRequest(inputMessage));
    }

    protected void execute() {

        if (!isRootDeviceMessage()) {
            log.finest("Ignoring useless embedded device/service advertisement message: " + getInputMessage());
            return;
        }

        RemoteDeviceIdentity rdIdentity = new RemoteDeviceIdentity(
                getInputMessage().getRootDeviceUDN(),
                getInputMessage().getMaxAge(),
                getInputMessage().getLocationURL(),
                getInputMessage().getInterfaceMacHeader(),
                getInputMessage().getLocalAddress()
        );
        log.fine("Received root device notification: " + rdIdentity);

        RemoteDevice rd;
        try {
            rd = new RemoteDevice(rdIdentity);
        } catch (ValidationException ex) {
            log.warning("Validation errors of device during discover: " + rdIdentity);
            for (ValidationError validationError : ex.getErrors()) {
                log.warning(validationError.toString());
            }
            return;
        }

        if (isRootDeviceAliveMessage()) {
            log.fine("Received root device ALIVE advertisement, descriptor location is: " + rdIdentity.getDescriptorURL());

            if (rdIdentity.getDescriptorURL() == null) {
                log.finer("Ignorning message without location URL header: " + getInputMessage());
                return;
            }

            if (rdIdentity.getMaxAgeSeconds() == null) {
                log.finer("Ignorning message without max-age header: " + getInputMessage());
                return;
            }

            // Add it to the registry, the registry will decide if it's just a refresh or really new
            RemoteDevice registeredDevice = getUpnpService().getRegistry().addDevice(rd);

            // But if it's really new we need to retrieve the descriptor
            if (registeredDevice != null && registeredDevice.getPhase().equals(Phase.DISCOVERED)) {
                getUpnpService().getConfiguration().getAsyncProtocolExecutor().execute(
                        new RetrieveRemoteDescriptors(getUpnpService(), registeredDevice)
                );
            }

        } else if (isRootDeviceByeByeMessage()) {
            log.fine("Received root device BYEBYE advertisement");
            getUpnpService().getRegistry().removeDevice(rd);
        }

    }

    protected boolean isRootDeviceMessage() {
        return getInputMessage().isRootDeviceMessage();
    }

    protected boolean isRootDeviceAliveMessage() {
        return getInputMessage().isRootDeviceAliveMessage();
    }

    protected boolean isRootDeviceByeByeMessage() {
        return getInputMessage().isRootDeviceByeByeMessage();
    }


}
