/*
	Copyright (C) 2022-2025 Mark Tyler

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program in the file COPYING.
*/

#include "qt5.h"



template < typename Tparser >
void MainWindow::TabUIelements<Tparser>::click_evaluate ()
{
	std::string result;

	mtQEX::BusyDialog busy ( &mainwindow, nullptr );

	busy.start_thread ( [this, &result]()
	{
		mpfr_prec_t const bits = (
			std::is_same<Tparser, mtDW::FloatParser>::value
			) ? (1 << mainwindow.mprefs.calc_float_bits) : 0;

		std::string	txt;
		QString		whole = m_text_input->toPlainText();
		QStringList	lines = whole.split ( '\n' );

		m_parser.variables().clear();

		if ( bits )
		{
			mpfr_set_default_prec ( bits );
		}

		int l = 0;
		int e = 0;

		for ( ; l < lines.size(); l++ )
		{
			txt = lines[l].toStdString();

			if (	txt.size() < 1
				|| txt[0] == '#'
				)
			{
				continue;
			}

			e = m_parser.evaluate ( txt.c_str() );
			if ( e )
			{
				break;
			}
		}

		if ( e )
		{
			char buf[128];
			result = "ERROR!\n";

			snprintf ( buf, sizeof(buf), "Line %i:\n", l+1 );

			result += buf;
			result += txt;
			result += '\n';

			size_t const pos = (size_t)m_parser.error_pos ();

			result += txt.substr ( 0, pos );
			result += "^\n";
			result += mtDW::get_error_text ( e );
		}

		if ( bits )
		{
			mpfr_free_cache();
		}
	});

	if ( result.size() == 0 )
	{
		// String is empty, so no error occurred. Get the number.
		result = m_parser.result().to_string_snip (
			(size_t)mainwindow.mprefs.calc_snip_size );
	}

	m_text_output->setPlainText ( result.c_str() );

	std::string title ( "Output " );

	title += print_digits_label ( m_parser.result(),
		(int)result.size() );

	m_group_box->setTitle ( title.c_str() );
}

template void MainWindow::TabUIelements<mtDW::FloatParser>::click_evaluate ();
template void MainWindow::TabUIelements<mtDW::DoubleParser>::click_evaluate ();
template void MainWindow::TabUIelements<mtDW::IntegerParser>::click_evaluate ();
template void MainWindow::TabUIelements<mtDW::RationalParser>::click_evaluate ();

