/*
 * 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.ValidationException;
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.message.IncomingDatagramMessage;
import org.teleal.cling.model.message.UpnpResponse;
import org.teleal.cling.model.message.discovery.IncomingSearchResponse;
import org.teleal.cling.protocol.ReceivingAsync;
import org.teleal.cling.protocol.RetrieveRemoteDescriptors;

import java.util.logging.Logger;


public class ReceivingSearchResponse extends ReceivingAsync<IncomingSearchResponse> {

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

    public ReceivingSearchResponse(UpnpService upnpService, IncomingDatagramMessage<UpnpResponse> inputMessage) {
        super(upnpService, new IncomingSearchResponse(inputMessage));
    }

    protected void execute() {

        // TODO: Some code duplication with ReceivingNotification

        // TODO: This is broken, there are responses which are NOT root device results (service type, device type)
        if (!isRootDeviceMessage()) {
            log.fine("Ignoring non-root device search response message: " + getInputMessage());
            return;
        }

        RemoteDeviceIdentity rdIdentity = new RemoteDeviceIdentity(
                getInputMessage().getRootDeviceUDN(),
                getInputMessage().getMaxAge(),
                getInputMessage().getLocationURL(),
                getInputMessage().getInterfaceMacHeader(),
                getInputMessage().getLocalAddress()
        );
        log.fine("Received root device search response: " + 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 (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)
            );
        }
    }

    protected boolean isRootDeviceMessage() {
        return getInputMessage().isSearchResponseRootDeviceMessage() ||
                getInputMessage().isSearchResponseRootDeviceUDNMessage();
    }


}
