#!/usr/bin/perl -w

# We do not want STDERR to clutter our screen.
open STDERR, ">/dev/null";

use strict;
use FindBin;
use lib "$FindBin::RealBin/../lib";
use Curses::UI;

my $cui = new Curses::UI ( -clear_on_exit => 1 );

my $win1 = $cui->add(
        'win1', 'Window',
        -border => 1,
        -title => 'My first Curses::UI window!',
        -pad => 2,
);

my $win2 = $cui->add(
        'win2', 'Window',
        -border => 1,
        -title => 'My second Curses::UI window!',
        -pad => 6,
);

my $popup = $win1->add(
        'popup', 'PopupBox',
        -x => 2,
        -y => 2,
        -sbborder => 1, 
        -values => [ 1, 2, 3, 4, 5 ],
        -labels => {
            1 => 'One',
            2 => 'Two', 
            3 => 'Three',
            4 => 'Four',
            5 => 'Five',
        },
);

my $but1 = $win1->add(
        'buttons', 'ButtonBox',
        -x => 2, 
        -y => 4, 
        -buttons => [
	    { -label => '< goto window 2 >', -value => 'goto2' },
            { -label => '< Quit >', -value => 'quit' },
	],
);
    
   
my $editor = $win2->add(
        'editor', 'TextEditor',
        -border => 1,
        -vscrollbar => 1,
        -wrapping => 1,
        -x => 2,
        -y => 2,
        -padright => 2,
        -padbottom => 3,
);

my $but2 = $win2->add(
        'buttons', 'ButtonBox',
        -x => 2,
        -y => -2,
        -buttons => [
	    { -label => '< goto window 1 >', -value => 'goto1' },
            { -label => '< Quit >', -value => 'quit' },
	],
);


$win1->returnkeys("\cN", "\cQ");
$win2->returnkeys("\cN", "\cQ");

MAINLOOP: for(;;) {
     WINDOW: foreach my $win_id ('win1','win2') {
            # Bring the current window on top
            $cui->ontop($win_id);

            # Get the window object.
            my $win = $cui->getobj($win_id);

            # Bring the focus to this window. Focus routines
            # will return a returnvalue (which is always
            # "LEAVE_CONTAINER" for a Container object) and
            # the last key that was pressed.
            my ($returnvalue, $lastkey) = $win->focus;
            
            # First check if the $lastkey is one of the
            # shortcut keys we created using returnkeys().
            if ($lastkey eq "\cN") {
                next WINDOW;
            } elsif ($lastkey eq "\cQ") {
                last MAINLOOP;
            }

            # Nope. Then we can assume that a button
            # was pressed. Check which button it was.

            # First get the button object of the focused window.
            my $btn = $win->getobj('buttons');

            # Get the value of the pressed button.
            my $button_value = $btn->get;

            # If the $button_value is 'quit', the Quit button was clicked.
            last MAINLOOP if $button_value eq 'quit';
     }
}

$cui->dialog("Bye bye!");

