package ballistics.utils.math.equations

import kotlin.math.abs

class EquationCalculatorSpan : AbstractEquationCalculator() {

    override fun calculate(
        x1: Double,
        x2: Double,
        f: (Double) -> Double,
    ): Double? {
        if (!check(x1, x2, f))
            return null

        iteration = 0
        var xl = x1
        var xr = x2

        var yl = f(xl)
        var yr = f(xr)
        var xmid = xl - ((xr - xl) / ((yr - value) - (yl - value))) * (yl - value)
        var ymid = f(xmid)

        var d = abs(ymid - value) * 10000.0
        while ((d > delta * 10000.0) && (iteration < maxIterations)) {
            if ((yl - value) * (ymid - value) < 0) {
                xr = xmid
                yr = ymid
            } else {
                xl = xmid
                yl = ymid
            }
            xmid = xl - ((xr - xl) / ((yr - value) - (yl - value))) * (yl - value)
            ymid = f(xmid)
            d = abs(ymid - value) * 10000.0
            iteration++
        }
        return if (iteration < maxIterations) {
            xmid
        } else {
            null
        }
    }
}
