package ballistics.utils.math.equations

import kotlin.math.abs

class EquationCalculator2Div : 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 xmid = (xl + xr) / 2.0
        var ymid = f(xmid)
        var y1 = f(xl)

        if ((y1 - value) * (ymid - value) < 0) {
            xr = xmid
        } else {
            xl = xmid
        }

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

            d = abs(ymid - value)
            iteration++
        }
        return if (iteration < maxIterations) {
            xmid
        } else {
            null
        }
    }
}
