import {Quality} from "./Quality.js";
import {vector_dot} from "../../vec/vector_dot.js";

/**
 * Verifies that the computed ball is indeed the miniball.
 *
 * This method should be called for testing purposes only; it may not be very efficient.
 * @param {Miniball} miniball
 * @return {Quality}
 */
export function miniball_compute_quality(miniball) {
    const support = miniball.support;
    const points = miniball.S;
    const center = miniball.center();
    const dimension_count = miniball.dim;


    let min_lambda = 1;
    let max_overlength = 0;
    let min_underlength = 0;
    let ball_error;

    let qr_error = support.representationError();

    support.findAffineCoefficients(center, miniball.lambdas);

    for (let k = 0; k < support.size(); ++k) {
        if (miniball.lambdas[k] <= min_lambda) {
            min_lambda = miniball.lambdas[k];
        }
    }

    for (let k = 0; k < points.size(); ++k) {

        for (let i = 0; i < dimension_count; ++i) {
            miniball.centerToPoint[i] = points.coord(k, i) - center[i];
        }

        const sqDist = vector_dot(miniball.centerToPoint, miniball.centerToPoint, dimension_count);

        ball_error = Math.sqrt(sqDist) - miniball.radius();

        if (ball_error > max_overlength) {
            max_overlength = ball_error;
        }

        if (support.isMember(k) && ball_error < min_underlength) {
            min_underlength = ball_error;
        }
    }

    return new Quality(
        qr_error,
        min_lambda,
        max_overlength / miniball.radius(),
        Math.abs(min_underlength / miniball.radius()),
        miniball.iteration,
        support.size()
    );
}
