using System;

using sharpallegro5;

using ALLEGRO_DISPLAY = System.IntPtr;
using ALLEGRO_BITMAP = System.IntPtr;
using ALLEGRO_TIMER = System.IntPtr;
using ALLEGRO_EVENT_QUEUE = System.IntPtr;
using ALLEGRO_FONT = System.IntPtr;

public class ex_keyboard_focus : AllegroExample
{
    /*
     *    Example program for the Allegro library.
     *
     *    This program tests if the ALLEGRO_KEYBOARD_STATE `display' field
     *    is set correctly to the focused display.
     */



    static ALLEGRO_DISPLAY display1;
    static ALLEGRO_DISPLAY display2;

    static void redraw(ALLEGRO_COLOR color1, ALLEGRO_COLOR color2)
    {
        al_set_target_backbuffer(display1);
        al_clear_to_color(color1);
        al_flip_display();

        al_set_target_backbuffer(display2);
        al_clear_to_color(color2);
        al_flip_display();
    }

    static int Main()
    {
        ALLEGRO_COLOR black;
        ALLEGRO_COLOR red;
        ALLEGRO_KEYBOARD_STATE kbdstate = new ALLEGRO_KEYBOARD_STATE();

        if (!al_init())
        {
            abort_example("Error initialising Allegro.\n");
            return 1;
        }

        if (!al_install_keyboard())
        {
            abort_example("Error installing keyboard.\n");
            return 1;
        }

        display1 = al_create_display(300, 300);
        display2 = al_create_display(300, 300);
        if (display1 == IntPtr.Zero || display2 == IntPtr.Zero)
        {
            abort_example("Error creating displays.\n");
            return 1;
        }

        black = al_map_rgb(0, 0, 0);
        red = al_map_rgb(255, 0, 0);

        while (true)
        {
            al_get_keyboard_state(ref kbdstate);
            if (al_key_down(ref kbdstate, ALLEGRO_KEY_ESCAPE))
            {
                break;
            }

            if (kbdstate.display == display1)
            {
                redraw(red, black);
            }
            else if (kbdstate.display == display2)
            {
                redraw(black, red);
            }
            else
            {
                redraw(black, black);
            }

            al_rest(0.1);
        }

        return 0;
    }
}