#include <math.h>
#include <ostream>
#include <iostream>
#include <boost/math/tools/roots.hpp>

#include "affine.h"

// Based on prototyping done in box4.py

double findpoint_curve(double x, double y, double adc_inphase, double ssa_slope, double ssa_slope_offset)
{
	double mag = sqrt(x*x+y*y);
	double lhs = x/mag;
	double adc_from_dac = ssa_slope_offset + ssa_slope*mag;
	double rhs = adc_inphase/adc_from_dac;
	// std::cout << x << " " << y << " " << adc_inphase << " " << (lhs-rhs) << std::endl;
	return lhs - rhs;
}

// https://stackoverflow.com/questions/59992122/how-to-pass-some-constants-in-boostss-brent-find-minima
struct box_func {
	double y;
	double adc;
	double ssa_slope;
	double ssa_slope_offset;
	box_func(double _y, double _adc, double _ssa_slope, double _ssa_slope_offset) :
		y(_y), adc(_adc), ssa_slope(_ssa_slope), ssa_slope_offset(_ssa_slope_offset) {}
	double operator()(double const& x)
	{
		return findpoint_curve(x, y, adc, ssa_slope, ssa_slope_offset);
	}
};

double findpoint(double dac_qmax, double adc_inphase, double ssa_slope, double ssa_slope_offset)
{
	double bracket_min = 0.0;
	double bracket_max = 1.0;
	const boost::uintmax_t maxit = 40;
	boost::uintmax_t it = maxit;
	boost::math::tools::eps_tolerance<double> tol(30);
	using boost::math::tools::toms748_solve;
	std::cout << "findpoint(" << dac_qmax << ", " << adc_inphase << ")" << std::endl;
	try {
		std::pair<double,double> r = toms748_solve(
			box_func(dac_qmax, adc_inphase, ssa_slope, ssa_slope_offset),
			bracket_min, bracket_max, tol, it);
		std::cout << "  x at minimum = " << r.first << ", f(" << r.first << ") = " << r.second;
		if (it < maxit) {
			std::cout << ",\n  success after " << it << " iterations." << std::endl;
		} else {
			std::cout << ",\n  failure after " << it << " iterations!" << std::endl;
		}
		return r.first;
	} catch (const std::exception& e) {
		std::cout << "\n""Message from thrown exception was:\n   " << e.what() << std::endl;
	}
	return 0.0;  // fault
}

void max_setup(double drv_max, double react_fraction, double ssa_slope, double ssa_slope_offset, double dac_minmax[4])
{
	// Step 1: find coordinates of max ADC (and therefore Fwd and DAC)
	// based on dac_max, react_fraction, dac_to_adc(), and of course fwd_scale
	double dac_imax = drv_max*sqrt(1-react_fraction);
	double dac_qmax = drv_max*sqrt(react_fraction);

	// Step 2: find on-real-axis coordinates, zero detuning
	// double adc_ineed = dac_to_adc(dac_imax);
	double adc_ineed = ssa_slope_offset + ssa_slope*dac_imax;

	// Step 3: solve for left edge of DAC clip box
	double dac_imin = findpoint(dac_qmax, adc_ineed, ssa_slope, ssa_slope_offset);

	// Results (scale by 79500 to get actual FPGA register values)
	dac_minmax[0] = dac_imin;
	dac_minmax[1] = dac_imax;
	dac_minmax[2] = -dac_qmax;
	dac_minmax[3] = dac_qmax;
	// Exception handling not yet included
}

// Very non-C++-like
#define dac_to_adc(dac) (ssa_slope_offset + ssa_slope*(dac))
#define adc_to_dac(adc) (((adc)-ssa_slope_offset) /  ssa_slope)

int op_setup(
	double adc_want,
	double drv_max,
	double react_fraction,
	double ssa_slope,
	double ssa_slope_offset,
	double dac_minmax[4])
{
	double peak_minmax[4];
	max_setup(drv_max, react_fraction, ssa_slope, ssa_slope_offset, peak_minmax);
	std::cout << "dac_imin " << peak_minmax[0] << std::endl;
	std::cout << "dac_imax " << peak_minmax[1] << std::endl;
	std::cout << "dac_qmin " << peak_minmax[2] << std::endl;
	std::cout << "dac_qmax " << peak_minmax[3] << std::endl;
	std::cout << "Margins not yet included" << std::endl;
	// Note that the "expensive" step above is independent of adc_want,
	// and could be skipped if only adc_want changes, remembering peak_minmax.
	//
	double adc_ineed = dac_to_adc(peak_minmax[1]);
	double op_scale = adc_want / adc_ineed;
	if (op_scale > 1.0) {
		std::cout << "Can't operate at " << adc_want << " ADC, max is " << adc_ineed << std::endl;
		return 0;
	}
	double reac_actual = peak_minmax[2] / peak_minmax[0];
	// double adc_qphase = adc_ineed * reac_actual;
	double reac_mag = sqrt(1 + reac_actual*reac_actual);
	double adc_mag = adc_want * reac_mag;
	//
	double dac_w_imax = adc_to_dac(adc_want);
	double dac_w_mag = adc_to_dac(adc_mag);
	double dac_w_imin = dac_w_mag / reac_mag;
	double dac_w_qmax = dac_w_mag * reac_actual / reac_mag;
	dac_minmax[0] = dac_w_imin;
	dac_minmax[1] = dac_w_imax;
	dac_minmax[2] = -dac_w_qmax;
	dac_minmax[3] = dac_w_qmax;
	return 1;
}

#ifdef SELFTEST
// Still pure test mode, trying to match results of box4.py
int main(int argc, char *argv[])
{
	double ssa_slope = 0.942;
	double ssa_slope_offset = -0.209;
	double drv_max=0.6;
	double react_fraction=0.4;
	double dac_minmax[4];
	double adc_want=0.19;
	if (argc>1) {
		adc_want=atof(argv[1]);
	}
	std::cout << "adc_want = " << adc_want << std::endl;

	if (op_setup(adc_want, drv_max, react_fraction, ssa_slope, ssa_slope_offset, dac_minmax)) {
		std::cout << "DAC x min/max " << dac_minmax[0] << " " << dac_minmax[1] << std::endl;
		std::cout << "DAC y min/max " << dac_minmax[2] << " " << dac_minmax[3] << std::endl;
		return 0;
	}
	return 1;
}
#endif
