package space.nstart.pcp.pcp_mission_planing_service.service

import org.springframework.beans.factory.ObjectProvider
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToFlux
import space.nstart.pcp.pcp_types_lib.dto.ballistics.ExactTimePositionRequestDTO
import space.nstart.pcp.pcp_types_lib.dto.ballistics.OrbPointDTO
import space.nstart.pcp.pcp_types_lib.dto.ballistics.ObjViewRequestDTO
import space.nstart.pcp.pcp_types_lib.dto.ballistics.PointViewParamDTO
import space.nstart.pcp.pcp_types_lib.dto.ballistics.RadioVisibilityAreaDTO
import space.nstart.pcp.pcp_types_lib.dto.ballistics.SquareViewParamDTO
import space.nstart.pcp.pcp_types_lib.dto.ballistics.SquareViewParamsWithPointsDTO
import space.nstart.pcp.pcp_types_lib.utils.UtcDateTimes
import java.time.LocalDateTime


@Service
class BallisticsService(webClientBuilderProvider: ObjectProvider<WebClient.Builder>){
    private val webClientBuilder: WebClient.Builder = webClientBuilderProvider.ifAvailable ?: WebClient.builder()

    @Value("\${settings.ballistics-service:ic-service}")
    val url = ""

    private fun client() = webClientBuilder.baseUrl(url).build()


    fun mplSquare(req : ObjViewRequestDTO) =
        client()
            .post()
            .uri("/api/obj-view/mpl-square")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(req)
            .retrieve()
            .bodyToFlux<SquareViewParamDTO>()
            .toIterable()


    fun mplPoints(req : ObjViewRequestDTO) =
        client()
            .post()
            .uri("/api/obj-view/mpl-point")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(req)
            .retrieve()
            .bodyToFlux<PointViewParamDTO>()
            .toIterable()


    fun rva(id : Long,
            tn : LocalDateTime,
            tk : LocalDateTime) =
        client()
            .get()
            .uri("/api/satellites/{id}/rva?time_start={time_start}&time_stop={time_stop}",
                id,
                UtcDateTimes.format(tn),
                UtcDateTimes.format(tk))
            .retrieve()
            .bodyToFlux<RadioVisibilityAreaDTO>()
            .toIterable()


    fun cellCovering(cell : Long) =
        client()
            .get()
            .uri("/api/obj-view/cell-coverage/{cell}", cell)
            .retrieve()
            .bodyToFlux<SquareViewParamsWithPointsDTO>()
            .toIterable()


    fun exactTime(sat : Long, req : ExactTimePositionRequestDTO) =
        client()
            .post()
            .uri("/api/satellites/{satelliteId}/extract-time", sat)
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(req)
            .retrieve()
            .bodyToFlux<OrbPointDTO>()
            .toIterable()


}
