import 'dart:math';

import 'package:surface_tension_calculator/scripts/rk4.dart';

/// ========== FINDING OPTIMAL PARAMETERS for BASHFORTH-ADAMS SOLUTION ==========
void findOptimalParameters(
  List<double> posEdgePoints,
  List<double> negEdgePoints,
  List<double> aRangeRadCurv,
  List<double> bRangeShapeFact,
  List<double> xRange,
  List<double> tRangeAngle,
  List<dynamic> params,
  List<dynamic> ticks,
) {
  var rk4PosTable = makeRK4Table(posEdgePoints);
  var rk4NegTable = makeRK4Table(negEdgePoints);

  double minimumRMSD = 999999.0;
  List<double> bestParameters = [0, 0, 0, 0];

  for (var aRadCurv in aRangeRadCurv) {
    for (var bShapeFact in bRangeShapeFact) {
      for (var x in xRange) {
        for (var tAngle in tRangeAngle) {
          double fTotalDiffSquared = 0.0;
          rk4PosTable[0][3] = x;
          rk4PosTable[0][4] = tAngle;
          rk4NegTable[0][3] = x;
          rk4NegTable[0][4] = tAngle;
          fTotalDiffSquared += bashforthAdamsRK4(
            rk4PosTable,
            aRadCurv,
            bShapeFact,
            1.0,
          );
          fTotalDiffSquared += bashforthAdamsRK4(
            rk4NegTable,
            aRadCurv,
            bShapeFact,
            -1.0,
          );

          double currentRMSD = sqrt(
            fTotalDiffSquared / (posEdgePoints.length + negEdgePoints.length),
          );
          if (currentRMSD < minimumRMSD) {
            minimumRMSD = currentRMSD;
            bestParameters = [aRadCurv, bShapeFact, x, tAngle];
          }
        }
        ticks.add("#");
      }
    }
  }

  double aRadCurv = bestParameters[0];
  double bShapeFact = bestParameters[1];
  double x = bestParameters[2];
  double tAngle = bestParameters[3];
  // double st = (9.8 * aRadCurv) / bShapeFact;
  params.add((minimumRMSD, aRadCurv, bShapeFact, x, tAngle));
}
