package org.nstart.dep265.requestservice.mapper

import org.nstart.dep265.requestservice.dto.RouteAngleRangeDto
import org.nstart.dep265.requestservice.dto.RouteDto
import org.springframework.stereotype.Component
import space.nstart.pcp.pcp_types_lib.dto.routes.AngleRangeDto
import space.nstart.pcp.pcp_types_lib.dto.routes.RoutePassportDto
import kotlin.math.abs

@Component
class RoutePassportMapper {
    fun toRouteDto(routePassportDto: RoutePassportDto): RouteDto =
        RouteDto(
            routeId = routePassportDto.routeId,
            intervalBegin = routePassportDto.intervalBegin,
            intervalEnd = routePassportDto.intervalEnd,
            rollAngle = routePassportDto.rollAngle.toAbsoluteRange(),
            geometry = routePassportDto.geometry,
        )

    private fun AngleRangeDto.toAbsoluteRange(): RouteAngleRangeDto {
        val minAbs = abs(min.toDouble())
        val maxAbs = abs(max.toDouble())
        val absoluteMin = if (min.signum() <= 0 && max.signum() >= 0) {
            0.0
        } else {
            minOf(minAbs, maxAbs)
        }
        val absoluteMax = maxOf(minAbs, maxAbs)

        return RouteAngleRangeDto(
            min = absoluteMin,
            max = absoluteMax,
        )
    }
}
