#include <errno.h>
#include <newt.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "perror.h"
#include "windows.h"

/* this makes no attempt to look nice */
static void vwindow(int left, int top, int width, int height, char * title, 
		    char * message, va_list args) {
    newtComponent b1, t, f;
    char * buf = NULL;
    int size = 0;
    int i = 0;

    do {
	size += 1000;
	if (buf) free(buf);
	buf = malloc(size);
	i = vsnprintf(buf, size, message, args);
    } while (i == size);

    newtOpenWindow(left, top, width, height, title);

    b1 = newtButton((width - 8) / 2, height - 4, "Ok");
    t = newtTextbox(1, 1, width - 2, height - 5, NEWT_TEXTBOX_WRAP);
    newtTextboxSetText(t, buf);
    f = newtForm(NULL, NULL, 0);

    free(buf);

    newtFormAddComponents(f, t, b1, NULL);

    newtRunForm(f);
 
    newtFormDestroy(f);
    newtPopWindow();
}

void winMessage(int left, int top, int width, int height, char * title,
		char * message, ...) {
    va_list args;

    va_start(args, message);
    vwindow(left, top, width, height, title, message, args);
    va_end(args);
}

void messageWindow(char * title, char * message, ...) {
    va_list args;

    va_start(args, message);
    vwindow(17, 4, 45, 15, title, message, args);
    va_end(args);
}

void errorWindow(char * str) {
    char * a;

    a = alloca(strlen(str) + 5);
    strcpy(a, str);
    strcat(a, ": %s");

    messageWindow("Error", str, strerror(errno));
}

void winStatus(int width, int height, char * title,
		char * text, ...) {
    newtComponent t, f;
    char * buf = NULL;
    int size = 0;
    int i = 0;
    va_list args;

    va_start(args, text);

    do {
	size += 1000;
	if (buf) free(buf);
	buf = malloc(size);
	i = vsnprintf(buf, size, text, args);
    } while (i == size);

    va_end(args);

    newtOpenWindow(40 - (width / 2), 11 - (height / 2), width, height, title);

    t = newtTextbox(1, 1, width - 2, height - 2, NEWT_TEXTBOX_WRAP);
    newtTextboxSetText(t, buf);
    f = newtForm(NULL, NULL, 0);

    free(buf);

    newtFormAddComponent(f, t);

    newtDrawForm(f);
    newtRefresh();
    newtFormDestroy(f);
}
