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.DeviceOperationalStatus;
import eu.teraflow.automation.model.DeviceRole;
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> ztpAdd(DeviceRole deviceRole) {

        final var deviceUni = contextService.getDevice(deviceRole.getDeviceRoleId().getDeviceId());

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

                                final var initialConfig =
                                        deviceService.getInitialConfiguration(
                                                deviceRole.getDeviceRoleId().getDeviceId());

                                device.setDeviceOperationalStatus(DeviceOperationalStatus.ENABLED);

                                initialConfig
                                        .subscribe()
                                        .with(
                                                deviceConfig -> {
                                                    device.setDeviceConfiguration(deviceConfig);
                                                    deviceService.configureDevice(device);

                                                    LOGGER.infof("Received response %s", device);
                                                });
                            }
                        });

        return deviceUni;
    }
}
