/**
 * File:
 * Package:	TV cards configuration
 * Summary:	User interface functions.
 * Authors:
 *
 * $Id: irc_ui.ycp 22512 2005-03-14 14:35:26Z lslezak $
 *
 */

{

textdomain "tv";

import "Label";
import "Popup";
import "Require";
import "Service";
import "Tv";
import "Wizard";
import "Wizard_hw";


include "tv/helps.ycp";
include "tv/misc.ycp";

/**
 * Dialog for testing IRC
 * @return boolean false when Abort was pressed or some problems occured
 */
define boolean IRCTestPopup (string config_file, string mod, boolean modified) ``{

    string orig_module	= "";
    string orig_config	= "";
    boolean orig_start	= false;

    /**
     * internal function
     * start with temporary LIRC configuration to enable the test
     * @return empty string on success, error message otherwise
     */
    define string lirc_tmp_start () ``{

	if (!modified)
	    return "";
	// store old configuration
	orig_module = (string) SCR::Read (.sysconfig.lirc.LIRC_MODULE);
	if (SCR::Read (.target.size, "/etc/lircd.conf") != -1)
	{
	    orig_config = Tv::tmpdir + "/lircd.conf";
	    SCR::Execute (.target.bash,"/bin/cp /etc/lircd.conf "+orig_config);
	    y2milestone("copy /etc/lirc.conf to %1", orig_config);
	}
	// 1. copy new config file, update sysconfig value

	SCR::Write (.sysconfig.lirc.LIRC_MODULE, mod);
	SCR::Write (.sysconfig.lirc, nil);

	if (config_file != "/etc/lircd.conf")
	    SCR::Execute (.target.bash,
		sformat ("/bin/cp %1 /etc/lircd.conf", config_file));

        // 2. start service (what if it is running?)
	orig_start = (Service::Status ("lirc") == 0);

	map out = $[];
	//when module cannot be loaded, Runlevel returns 0 -> use target.bash
	if (orig_start)
	    out = (map) SCR::Execute (.target.bash_output, "rclirc restart");
	else
	    out = (map) SCR::Execute (.target.bash_output, "rclirc start");
	return out["stderr"]:"";
    }

    /**
     * internal function
     * return LIRC configuration to original state after testing
     */
    define boolean lirc_tmp_stop () ``{

	if (!modified)
	    return true;
	if (orig_config != "")
	{
	    y2milestone("copy %1 to /etc", orig_config);
	    SCR::Execute (.target.bash,
		sformat ("/bin/cp %1 /etc/lircd.conf ", orig_config));
	}
	SCR::Write (.sysconfig.lirc.LIRC_MODULE, orig_module);
	SCR::Write (.sysconfig.lirc, nil);
	if (orig_start)
	    Service::RunInitScript ("lirc", "restart");
	else
	    Service::RunInitScript ("lirc", "stop");
	return true;
    }

    UI::OpenDialog(`opt(`decorated), `HBox(`HSpacing(1.5),
    `VBox(
        `VSpacing(1),
        // Wait text label
        `Label(_("Initializing -- please wait...")),
        `VSpacing(1),
        `PushButton(`id(`done), `opt(`default), Label::AbortButton()),
        `VSpacing(1)),
    `HSpacing(1.5)
    ));

    string start = lirc_tmp_start ();
    if (start != "")
    {
	// error popup text
	ErrorWithDetails (_("Starting the 'lirc' service failed."), start);
	UI::CloseDialog();
	lirc_tmp_stop ();
	return false;
    }

    // test if IRC device is present
    /* FIXME device is created dynamically
    if (SCR::Execute(.target.bash, "echo 2>/dev/null < /dev/lirc") != 0)
    {
	// error popup text
	Popup::Error (_("No IRC device is present.
(Maybe wrong module was loaded.)"));
	UI::CloseDialog();
	lirc_tmp_stop ();
	return false;
    }
    */

    // 3. run irw -> test
    SCR::Execute (.background.run_output, "/usr/bin/irw");

    UI::CloseDialog();
    // construct the dialog
    UI::OpenDialog(`opt(`decorated), `HBox(`HSpacing(1.5),
    `VSpacing(18),
    `VBox(
        `HSpacing(60),
        `VSpacing(0.5),
	// Popup label (heading)
        `Label(_("IRC Test")),
	// Popup label (info text), please keep translation
        `Label(_("Push the buttons of your IR controller to test its functionality.")),
        `VSpacing(0.5),
        `LogView (`id (`irw), "", 10, 0),
        `VSpacing(0.5),
        `PushButton(`id(`done), `opt(`default), Label::OKButton()),
        `VSpacing(0.5)),
    `HSpacing(1.5)
    ));

    // read the irw output
    string test_output = "";
    any ret = nil;
    do
    {
	ret = UI::PollInput();
        if ((boolean) SCR::Read(.background.output_open) &&
	    (integer) SCR::Read(.background.newlines)>0)
        {
	    list<string> newout = (list<string>)SCR::Read(.background.newout);
            // read the output line from irw:
            test_output = (string) newout[0]:nil;
	    if (test_output != nil)
		UI::ChangeWidget (`id(`irw), `LastLine, test_output + "\n");
        }
	else if (!(boolean)SCR::Read(.background.output_open))
	{
	    // error text
	    Popup::Error(_("The testing application is not responding."));
	    ret = `ok;
	}
    }
    while (ret == nil);

    SCR::Execute(.background.kill, nil);
    lirc_tmp_stop ();
    UI::CloseDialog();

    return true;
}


/**
 * Dialog for seting up IRC
 * @param run from irc.ycp client? (=not from tv module)
 */
define any IRCDialog (boolean alone) ``{

    // skip IRC dialgo for DVB cards
    // TODO: skip for all DVB cards?
    if (alone == false && Tv::current_card["dvb"]:false == true)
    {
	return `next;
    }

    // For translators: Caption of the dialog
    string caption = _("Infrared Control Configuration");

    boolean use_irc	= Tv::use_irc;
    string irc_config	= Tv::irc_config;
    string irc_module	= Tv::irc_module;
    list mods		= Tv::irc_modules_list;

    if (irc_module == "")
	irc_module = Tv::GetIRCModule();
    // FIXME irc_module should be loaded when new TV card is chosen...

    if (!alone && Tv::current_card["radio"]:false)
	return `next;

    /*
    string startdir = "/usr/share/lirc/remotes/";
    list remotes_items = [];
    foreach (string control, (list<string>) Tv::remotes, ``{
	list aslist = splitstring (control, "/");
	string last = aslist [ size(aslist)-1 ]:"";
	if (issubstring (last, "lircd.conf."))
	    last = substring (last, size ("lircd.conf."));
	if (last != "")
	    remotes_items = add (remotes_items, `item(`id(control), last));
    });

    if (irc_config == "/etc/lircd.conf")
	remotes_items = add (remotes_items,
	    `item(`id("/etc/lircd.conf"), _("current (/etc/lircd.conf)")));
    */

    term con = `HBox (`HSpacing (3), `VBox (
        `VSpacing (2),
        `RadioButtonGroup(`id(`rd),
	    `Left(`HVSquash(`VBox (
                `Left (`RadioButton(`id(`no), `opt (`notify),
		    // radio button label
		    _("Do No&t Use IRC"), !use_irc)),
                `Left(`RadioButton(`id(`yes), `opt (`notify),
		    // radio button label
		    _("&Use IRC"), use_irc)))))
	),
        `VSpacing (0.5),
	// frame label
	`Frame (_("IRC Settings"), `HBox(`HSpacing (),
	    `VBox(
		`VSpacing (),
		/*
		`ReplacePoint (`id(`configs),
		`HBox(
		    // combobox label
		    `ComboBox(`id(`config), `opt(`hstretch),
			_("IRC Config File"), remotes_items),
		    `VBox(
			`Label (""),
			// button label
			`PushButton(`id(`brow),`opt(`key_F7), _("M&ore..."))
		    )
		)),
		*/
		`ComboBox (`id(`mods), `opt(`notify, `hstretch),
		    // combobox label
		    _("Kernel Module"), mods),
		`Left(
		    `CheckBox (`id(`desc_ch), `opt (`notify),
			//checkbox label
			_("Show Module Description"), false)
		),
		`ReplacePoint (`id(`rp), `Empty ()),
		`VSpacing (0.5),
		`Right(
		    // button label
		    `PushButton (`id(`test), `opt(`key_F6), _("&Test"))),
		`VSpacing (0.5)
	    ), `HSpacing ()
	)),
	`VStretch ()
    ), `HSpacing(3));


    Wizard::SetContentsButtons ( caption, con, IRCDialogHelp (),
	Label::BackButton (), alone?Label::FinishButton():Label::NextButton ());


    foreach (symbol widget, [`mods, `test, `desc_ch],``{
	UI::ChangeWidget (`id (widget), `Enabled, use_irc);
    });

//    UI::ChangeWidget (`id(`config), `Value, irc_config);

    if (contains (mods, irc_module))
	UI::ChangeWidget (`id(`mods), `Value, irc_module);

    symbol ret = nil;
    do
    {
	ret = (symbol) tvUserInput();

//	irc_config = (string) UI::QueryWidget (`id(`config),  `Value);

	if (irc_module != (string) UI::QueryWidget (`id(`mods),  `Value))
	{
	    irc_module = (string) UI::QueryWidget (`id(`mods),  `Value);
	    if ((boolean) UI::QueryWidget (`id(`desc_ch), `Value))
		UI::ChangeWidget (`id(`desc),`Value,
		    Tv::irc_modules [irc_module]:"");
	}
	if (ret == `desc_ch)
	{
	    if ((boolean) UI::QueryWidget (`id(`desc_ch), `Value))
	    {
		if (Tv::irc_modules == $[])
		{
		    UI::OpenDialog (
			Wizard_hw::SpacingAround (
			    // popup label (waiting for other action):
			    `Label(_("Please wait while the list
of kernel module descriptions is retrieved...
")),
			    1.5, 1.5, 0.5, 0.5
			)
		    );
		    Tv::LoadIRCModulesDescription();
		    UI::CloseDialog();
		}
		UI::ReplaceWidget (`id(`rp), `VSquash(`HBox (
		    `VSpacing (3),
		    `RichText (`id(`desc), `opt (`shrinkable),
			Tv::irc_modules [irc_module]:"")
		)));
	    }
	    else
		UI::ReplaceWidget (`id(`rp), `Empty());
	}

        if (ret == `yes || ret == `no)
	{
            use_irc = (ret == `yes);
	    if (use_irc)
	    {
		boolean lirc_installed = Require::AreAllPackagesInstalledTarget(["lirc"]);

		if (!Require::RequireAndConflictTarget (["lirc"], [],
		// popup label (install required application?)
		_("For using infrared devices, package 'lirc' is required.
Install it now?
")))
		{
		    use_irc = false;
		    UI::ChangeWidget (`id(`rd), `CurrentButton, `no);
		}
		else
		{
		    if (lirc_installed == false)
		    {
			// the package has been just installed - make ini-agent reread the config file
			SCR::UnmountAgent(.sysconfig.lirc);
		    }
		}
	    }

	    foreach (symbol widget, [`mods, `test, `desc_ch],``{
		UI::ChangeWidget (`id (widget), `Enabled, use_irc);
	    });
	}
	/*
	if (ret == `brow)
	{
	    string file = UI::AskForExistingFile (startdir, "*", "");
	    if (file != nil)
	    {
		remotes_items = union (remotes_items, [`item(`id(file), file)]);
		UI::ReplaceWidget (`id(`configs), `HBox(
		    `ComboBox(`id(`config), `opt(`hstretch),
			_("IRC Config File"), remotes_items),
		    `VBox(`Label (""),
			`PushButton(`id(`brow),`opt(`key_F7), _("Mo&re..."))))
		);
		UI::ChangeWidget (`id(`config), `Value, file);
	    }

	}
	*/
	if (ret == `test)
	{
	    IRCTestPopup (irc_config, irc_module, (use_irc != Tv::use_irc ||
		irc_module != Tv::irc_module || irc_config != Tv::irc_config));
	}

    } while (!contains ([`back, `abort, `cancel, `next, `ok], ret));

    if (ret == `next && (use_irc != Tv::use_irc || irc_module != Tv::irc_module
			 || irc_config != Tv::irc_config))
    {
	Tv::irc_modified = true;
	Tv::use_irc = use_irc;
	Tv::irc_module = irc_module;
	Tv::irc_config = irc_config;
    }
    return ret;
}


/* EOF */
}
