#!/usr/bin/perl

use strict;

use lib qw(/usr/lib/libDrakX);
use standalone;
use common;

# we need ugtk2 to build a gtk2 interface easily
use ugtk2 qw(:all);
# we need this so that libconf can generate GUI
use Libconf::GUI::Gtk2 qw(:generators :builders);

use Libconf::Glueconf::System::Autologin;
use Libconf::Glueconf::System::Desktop;

# for debugging purpose
use Data::Dumper;

# we ask glueconf to give us the structure representing /etc/sysconfig/autologin
my $autologin = new Libconf::Glueconf::System::Autologin('/etc/sysconfig/autologin');
my $desktop = new Libconf::Glueconf::System::Desktop('/etc/sysconfig/desktop');

# we build the window
my $window = Gtk2::Window->new('toplevel');
$window->signal_connect(delete_event => sub { ugtk2->exit(0) });
$window->set_position('center');
$window->set_title(N("autologin configuration"));
$window->set_size_request(500, 400);

gtkadd($window,
       gtkpack_(Gtk2::VBox->new(0,10),
                1, create_packtable({ col_spacings => 5, row_spacings => 5 },
                    [
                     # first control : we put the label, and ask libconf to build the best widget for the key AUTOLOGIN of $autologin
                     new Gtk2::Label(N("Activate autologin")),
                     my $widget_AUTOLOGIN = getBestWidget($autologin, '{AUTOLOGIN}'),
                    ],
                    [
                     # second control : we put the label, and ask libconf to build the best widget for the key USER of $autologin
                     new Gtk2::Label(N("User")),
                     my $widget_USER = getBestWidget($autologin, '{USER}'),
                    ],
                    [
                     # third control : we put the label, and ask libconf to build the best widget it can, for the key DESKTOP of $desktop
                     new Gtk2::Label(N("Window Manager")),
                     my $widget_WM = getBestWidget($desktop, '{DESKTOP}'),
                    ]
                    ),
                0, gtkadd(gtkset_layout(Gtk2::HButtonBox->new, 'end'),
                          gtksignal_connect(new Gtk2::Button(N("OK")), clicked => sub { save_exit() }),
                          gtksignal_connect(new Gtk2::Button(N("Cancel")), clicked => sub { cancel_exit() })
                         ),
               )
      );


# we make everything visible in the window
$window->show_all;

#and we start the Gtk2 main loop.
Gtk2->main;


sub save() {
    $autologin->{AUTOLOGIN} = $widget_AUTOLOGIN->{value};
    $autologin->{USER} = $widget_USER->{value};
    $autologin->{EXEC} = '/usr/X11R6/bin/startx.autologin';
    $desktop->{DESKTOP} = $widget_WM->{value};

    $autologin->writeConf;
    $desktop->writeConf;
}

sub save_exit() {
    # we saves the modifications
    save();
    # we exit the gtk2 main loop
    Gtk2->main_quit;
}

# the function called when the user clicks on the Cancel button
sub cancel_exit() {
    # we exit the gtk2 main loop
    Gtk2->main_quit;
}
