using System;

using sharpallegro5;

using ALLEGRO_DISPLAY = System.IntPtr;
using ALLEGRO_TEXTLOG = System.IntPtr;
using ALLEGRO_EVENT_QUEUE = System.IntPtr;

public class AllegroExample : Allegro
{
#if ALLEGRO_POPUP_EXAMPLES

    static ALLEGRO_TEXTLOG textlog = NULL;

    public static void abort_example(string format, params object[] arg)
    {
        //char str[1024];
        //va_list args;
        string str;
        ALLEGRO_DISPLAY display;

        //va_start(args, format);
        //vsnprintf(str, sizeof str, format, args);
        //va_end(args);
        str = string.Format(format, arg);

        display = al_is_system_installed() ? al_get_current_display() : NULL;
        al_show_native_message_box(display, "Error", "Cannot run example", str, null, 0);
        Environment.Exit(1);
    }

    public static void open_log()
    {
        textlog = al_open_native_text_log("Log", 0);
    }

    public static void open_log_monospace()
    {
        textlog = al_open_native_text_log("Log", ALLEGRO_TEXTLOG_MONOSPACE);
    }

    public static void close_log(bool wait_for_user)
    {
        if (textlog != IntPtr.Zero && wait_for_user)
        {
            ALLEGRO_EVENT_QUEUE queue = al_create_event_queue();
            al_register_event_source(queue, al_get_native_text_log_event_source(
               textlog));
            /* HACK */
            ALLEGRO_EVENT e = new ALLEGRO_EVENT();
            al_wait_for_event(queue, ref e);
            /* ---- */
            //al_wait_for_event(queue, NULL);
            al_destroy_event_queue(queue);
        }

        al_close_native_text_log(textlog);
        textlog = NULL;
    }

    public static void log_printf(string format, params object[] arg)
    {
        //char str[1024];
        string str;
        //va_list args;
        //va_start(args, format);
        //vsnprintf(str, sizeof str, format, args);
        //va_end(args);
        str = string.Format(format, arg);
        al_append_native_text_log(textlog, "%s", __arglist(str));
    }

#else

    public static void abort_example(string format, params object[] arg)
    {
        //va_list args;
        //va_start(args, format);
        //vfprintf(stderr, format, args);
        Console.Write(format, arg);
        //va_end(args);
        //exit(1);
        Environment.Exit(1);
    }

    public static void open_log()
    {
    }

    public static void open_log_monospace()
    {
    }

    public static void close_log(bool wait_for_user)
    {
        //(void)wait_for_user;
    }

    public static void log_printf(string format, params object[] arg)
    {
        //va_list args;
        //va_start(args, format);
        //vprintf(format, args);
        Console.Write(format, arg);
        //va_end(args);
    }

#endif

}