package eu.teraflow.automation;

import eu.teraflow.automation.context.ContextService;
import eu.teraflow.automation.device.Device;
import eu.teraflow.automation.device.DeviceService;
import eu.teraflow.automation.device.model.*;
import io.smallrye.mutiny.Uni;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.jboss.logging.Logger;

@ApplicationScoped
public class AutomationServiceImpl implements AutomationService {
    private static final Logger LOGGER = Logger.getLogger(AutomationServiceImpl.class);

    private final DeviceService deviceService;
    private final ContextService contextService;

    @Inject
    public AutomationServiceImpl(DeviceService deviceService, ContextService contextService) {
        this.deviceService = deviceService;
        this.contextService = contextService;
    }

    @Override
    public Uni<Device> addDevice(DeviceId deviceId) {

        final var deviceUni = contextService.getDevice(deviceId);

        deviceUni
                .subscribe()
                .with(
                        device -> {
                            if (!(device
                                    .getDeviceOperationalStatus()
                                    .toString()
                                    .equals(DeviceOperationalStatus.ENABLED.toString()))) {

                                final var initialConfig = deviceService.getInitialConfiguration(deviceId);

                                device.setDeviceOperationalStatus(DeviceOperationalStatus.ENABLED);

                                initialConfig
                                        .subscribe()
                                        .with(
                                                deviceConfig -> {
                                                    device.setDeviceConfiguration(deviceConfig);
                                                    deviceService.configureDevice(device);
                                                    LOGGER.infof("Received response %s", device);
                                                });
                            }
                        });

        return deviceUni;
    }
}
