/*
	Copyright (C) 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 "pizor_be.h"



int CommandLine::parse (
	int			const	argc,
	char	const * const *	const	argv
	)
{
	mtKit::Arg args ( [this]( char const * const filename )
	{
		try
		{
			printf ( "Filename: %s\n", filename );
		}
		catch (...)
		{
			return 1;
		}
		return 0;
	});

	auto print_version = []()
	{
		puts ( BIN_NAME " - Part of " VERSION "\n" );
		return 1;		// Stop parsing
	};

	auto print_help = [print_version]()
	{
		print_version ();
		puts ("For further information consult the man page "
			BIN_NAME "(1) or the mtCellEdit Handbook.\n");
		return 1;		// Stop parsing
	};

	int		stop = 0;

	args.add ( "-help",	stop, 1, print_help );
	args.add ( "-version",	stop, 1, print_version );
	args.add ( "dir",	m_output_dir );
	args.add ( "i",		m_input_filename );
	args.add ( "o",		m_output_filename );
	args.add ( "prefs",	m_prefs_filename );
	args.add ( "threads",	m_thread_total );
	args.add ( "v",		m_verbose, 1 );

	if ( args.parse ( argc, argv ) || stop )
	{
		return 1;		// Quit program
	}

	if ( m_thread_total < THREAD_TOTAL_MIN ||
		m_thread_total > THREAD_TOTAL_MAX
		)
	{
		fprintf ( stderr, "Invalid thread total: %i (%i..%i)\n",
			m_thread_total, THREAD_TOTAL_MIN, THREAD_TOTAL_MAX );
		return 1;
	}

	switch ( m_thread_total )
	{
	case -1:
		m_thread_total = mtkit_int_bound ( mtkit_cpu_threads()/2,
			1, THREAD_TOTAL_MAX );
		break;

	case 0:
		m_thread_total = mtkit_int_bound ( mtkit_cpu_threads(),
			1, THREAD_TOTAL_MAX );
		break;
	}

	if ( m_verbose )
	{
		std::cout << "CPU threads used = " << m_thread_total << "\n";
	}

	prefs_init ();

	return 0;			// Continue program
}

void CommandLine::prefs_init ()
{
	uprefs.add_int ( PREFS_WINDOW_X, mprefs.window_x, 50 );
	uprefs.add_int ( PREFS_WINDOW_Y, mprefs.window_y, 50 );
	uprefs.add_int ( PREFS_WINDOW_W, mprefs.window_w, 320 );
	uprefs.add_int ( PREFS_WINDOW_H, mprefs.window_h, 200 );
	uprefs.add_int ( PREFS_WINDOW_MAXIMIZED, mprefs.window_maximized, 0 );

	uprefs.set_invisible ( PREFS_WINDOW_X );
	uprefs.set_invisible ( PREFS_WINDOW_Y );
	uprefs.set_invisible ( PREFS_WINDOW_W );
	uprefs.set_invisible ( PREFS_WINDOW_H );
	uprefs.set_invisible ( PREFS_WINDOW_MAXIMIZED );

	uprefs.load ( m_prefs_filename, BIN_NAME );
}

