/**
 * File:	clients/autoinst_software.ycp
 * Package:	Autoinstallation Configuration System
 * Authors:	Anas Nashif (nashif@suse.de)
 * Summary:	Handle Package selections and packages
 *
 * $Id: software_auto.ycp 19969 2004-10-27 02:01:08Z nashif $
 */
{

    textdomain "autoinst";

    import "Wizard";
    import "Summary";
    import "Report";
    import "AutoinstConfig";
    import "AutoinstSoftware";
    import "Label";
    import "PackageAI";
 
    include "autoinstall/dialogs.ycp";

    any ret = nil;
    string func = "";
    map param = $[];

    /* Check arguments */
    if(size(WFM::Args()) > 0 && is(WFM::Args(0), string))
    {
	func = (string) WFM::Args(0);
	if(size(WFM::Args()) > 1 && is(WFM::Args(1), map))
	{
	    param = (map) WFM::Args(1);
	}
    }
    y2debug("func=%1", func);
    y2debug("param=%1", param);


    /**
     * Select packages
     * @return symbol
     */
    define symbol packageSelector() ``{
	string language = UI::GetLanguage(true);

	string title = _("Software Selection");
	string helptext = _("<p>
Select one of the following <b>base</b> selections and click <i>Detailed<i> to add
more <b>add-on</b> selections and packages.
</p>
");
	Pkg::TargetFinish ();
	// AutoinstSoftware::pmInit();

	Pkg::SourceStartManager(true);

        Wizard::CreateDialog();
        Wizard::SetDesktopIcon("software");

	Wizard::SetContents(title,
			    `HVCenter(`Label(_("Reading package database..."))),
			    helptext, false, true);

	list<string> available_base_selections = Pkg::GetSelections( `available, "base" );
	y2milestone ("available_base_selections %1", available_base_selections);
	list current_base_selections = Pkg::GetSelections( `selected, "base" );
	y2milestone ("current_base_selections %1", current_base_selections);

	// save the current base selection
	string save_selection = current_base_selections[0]:"default";

	// Construct a box with radiobuttons for each software base configuration
	term baseconfs_box = `VBox();

	// sort available_base_selections by order
	// $[ "order" : [ "name", "summary" ], .... ]

	map<string, list> sorted_base_selections = $[];
	foreach( string selection, available_base_selections,
		 ``{
	    map selection_data = Pkg::SelectionData (selection);
	    if (selection_data != nil)
	    {
		string order = selection_data["order"]:"";
		// use selection name as sort criteria if not given
		if (order == "")
		{
		    order = selection;
		}
		sorted_base_selections[order] = [selection, selection_data["summary"]:("'"+selection+"'")];
	    }
	});

	boolean selected = false;
	// construct display box in order
	foreach(string  order, list data, sorted_base_selections,
		``{
	    {
		if (AutoinstSoftware::base == "" && !selected)
		{
		    AutoinstSoftware::base = data[0]:"";
		    selected = true;
		}
		baseconfs_box = add( baseconfs_box, `Left(`RadioButton(`id(data[0]:""),     // id
								       `opt(`notify, `autoShortcut),
								       data[1]:"",              // descrption
								       (data[0]:"" == AutoinstSoftware::base)   )));
	    }
	});

	term contents = `HVSquash(
				  `VBox(
					`HSquash(
						 `VBox(
						       `Frame(
							      // Frame caption for software selection
							      _("Software"),
							      `VBox(
								    `VSpacing(0.3),
								    `RadioButtonGroup(`id(`baseconf),`opt(`notify), baseconfs_box),
								    `VSpacing(0.3)
								    )
							      ),
						       `VSpacing(),

						       // Push button that will pop up the detailed
						       // software selection (e.g. Multimedia, Games,
						       // KDE, Gnome, ... - not the individual packages!)
						       `PushButton( `id(`details),  _("&Detailed selection...") )
						       )
						 )
					)
				  );

	Wizard::SetContents(title, contents, helptext, true, true);
	// Wizard::DisableBackButton();
	Wizard::HideAbortButton();
	any ret = nil;
	boolean error_found = false;
	boolean selret = false;
	repeat
	    {
		ret = Wizard::UserInput();

		// get the newly selected base configuration
		string base_selection = (string) UI::QueryWidget( `id(`baseconf),`CurrentButton );

		// Inform the package manager on `next about the new (only about a NEW) selection
		// or if the selection has changed
		if (ret == `next)
		{
		    // set the new selection
		    boolean pkgret = Pkg::SetSelection( base_selection );
		    if (size(PackageAI::toinstall ) > 0)
		    {
			foreach(string p, PackageAI::toinstall, ``{
			    y2milestone("selecting package for installation: %1 -> %2", p, Pkg::PkgInstall(p));
			});
		    }
		}
		else if ( ret == `details )
		{
		    ret = `again;

		    Pkg::SetSelection( base_selection );

		    foreach(string addon, AutoinstSoftware::addons, ``{
			Pkg::SetSelection( addon );
		    });

		    Pkg::ActivateSelections();
		    if (size(PackageAI::toinstall) > 0)
		    {
			foreach(string p, PackageAI::toinstall, ``{
			    y2milestone("selecting package for installation: %1 -> %2", p, Pkg::PkgInstall(p));
			});
		    }

		    while ( ret == `again )
		    {
			ret = (symbol)WFM::CallFunction( "inst_packages", [ true, true ] );

			if ( ret == `accept )
			    ret = `next;
		    }
		}
	    }  until ( ret == `next  || ret == `back);

	Pkg::ActivateSelections();
	y2milestone("blah 1");
	list allpacs = Pkg::GetPackages(`selected, true);
	y2milestone("All packages: %1 ( %2 )", allpacs, size(allpacs));

	list<string> seladd = [];
	list<string> selbase = [];
	if ( ret != `back )
	{
	    seladd =  Pkg::GetSelections(`selected, "");
	    selbase =  Pkg::GetSelections(`selected, "base");
	}
	else
	{
	    seladd = AutoinstSoftware::addons;
	    selbase = [AutoinstSoftware::base];
	}



        PackageAI::toinstall = Pkg::FilterPackages(false, false, true, true);
	AutoinstSoftware::addons = seladd;
	AutoinstSoftware::base =   selbase[0]:"";

	Wizard::CloseDialog();
	return (symbol)ret;
    }


    /* create a  summary*/

    if(func == "Summary") {
	ret =  AutoinstSoftware::Summary();
    }
    else if (func == "Import") {
	ret = AutoinstSoftware::Import(param);
    }
    else if (func == "Reset") {
	AutoinstSoftware::Import($[]);
	ret =  $[];
    }
    else if (func == "Change")
    {
	ret  = packageSelector();
    }
    else if (func == "GetModified") {
	ret  = AutoinstSoftware::GetModified() || PackageAI::GetModified();
    }
    else if (func == "SetModified") {
	AutoinstSoftware::SetModified();
        ret = true;
    }
    else if (func == "Export") {
	ret = AutoinstSoftware::Export();
    }
    /* unknown function */
    else {
	y2error("unknown function: %1", func);
	ret = false;
    }

    y2debug("ret=%1", ret);
    y2milestone("Software auto finished");
    y2milestone("----------------------------------------");

    return ret;

/* Finish */
}
