package eu.teraflow.automation;

import automation.Automation;
import context.ContextOuterClass;
import eu.teraflow.automation.device.model.DeviceId;
import eu.teraflow.automation.device.model.Uuid;
import io.quarkus.grpc.GrpcService;
import io.smallrye.mutiny.Uni;
import javax.inject.Inject;

@GrpcService
public class AutomationGatewayImpl implements AutomationGateway {

    private final AutomationService automationService;

    @Inject
    public AutomationGatewayImpl(AutomationService automationService) {
        this.automationService = automationService;
    }

    @Override
    public Uni<Automation.DeviceRole> ztpGetDeviceRole(Automation.DeviceRoleId request) {
        return Uni.createFrom()
                .item(() -> Automation.DeviceRole.newBuilder().setDevRoleId(request).build());
    }

    @Override
    public Uni<Automation.DeviceRoleList> ztpGetDeviceRolesByDeviceId(
            ContextOuterClass.DeviceId request) {
        return Uni.createFrom().item(() -> Automation.DeviceRoleList.newBuilder().build());
    }

    @Override
    public Uni<Automation.DeviceRoleState> ztpAdd(Automation.DeviceRole request) {

        automationService.addDevice(getDeviceId(request.getDevRoleId().getDevId()));

        return Uni.createFrom()
                .item(
                        () ->
                                Automation.DeviceRoleState.newBuilder()
                                        .setDevRoleId(request.getDevRoleId())
                                        .build());
    }

    @Override
    public Uni<Automation.DeviceRoleState> ztpUpdate(Automation.DeviceRole request) {
        return Uni.createFrom()
                .item(
                        () ->
                                Automation.DeviceRoleState.newBuilder()
                                        .setDevRoleId(request.getDevRoleId())
                                        .build());
    }

    @Override
    public Uni<Automation.DeviceRoleState> ztpDelete(Automation.DeviceRole request) {
        return Uni.createFrom()
                .item(
                        () ->
                                Automation.DeviceRoleState.newBuilder()
                                        .setDevRoleId(request.getDevRoleId())
                                        .build());
    }

    @Override
    public Uni<Automation.DeviceDeletionResult> ztpDeleteAll(Automation.Empty empty) {
        return Uni.createFrom().item(() -> Automation.DeviceDeletionResult.newBuilder().build());
    }

    private DeviceId getDeviceId(ContextOuterClass.DeviceId serializedDeviceId) {

        Uuid uuid = new Uuid(serializedDeviceId.getDeviceUuid().getUuid());

        return new DeviceId(uuid);
    }
}
