

#include "WINGsP.h"



typedef struct W_Window {
    W_Class widgetClass;
    W_View *view;
    
    char *caption;
    char *wclass;
    char *wname;

    struct {
	unsigned int configured:1;
    } flags;
} _Window;



static WMArgument windowArguments[] = {
    {WARG_WIDTH,	(WMValue)400},
    {WARG_HEIGHT,	(WMValue)180},
    {WARG_CAPTION,	(WMValue)"Untitled"},
};





static void destroyWindow(_Window *win);


static void
handleEvents(XEvent *event, void *clientData)
{
    _Window *win = (_Window*)clientData;
    
    
    switch (event->type) {
     case DestroyNotify:
	destroyWindow(win);
	break;
    }
}


#ifdef WMAKER
WMWindow*
WMCreateWindow(WMScreen *screen, Window parent, WMArgument *argv, int argc)
#else
WMWindow*
WMCreateWindow(WMScreen *screen, WMArgument *argv, int argc)
#endif
{
    _Window *win;
    
    win = wmalloc(sizeof(_Window));
    memset(win, 0, sizeof(_Window));
	   
    win->widgetClass = WC_Window;

    win->view = W_CreateTopView(screen);
#ifdef WMAKER
    win->view->wmakerParent = parent;
#endif
    if (!win->view) {
	free(win);
	return NULL;
    }

    
    WMCreateEventHandler(win->view, ExposureMask|StructureNotifyMask
			 |FocusChangeMask, handleEvents, win);

    if (!WMConfigureWindow(win, argv, argc)) {
	W_DestroyView(win->view);
	return NULL;
    }
    
    return win;
}



static int
configureWindowArg(_Window *win, WMArgument *arg)
{
    switch (arg->argument) {	
     case WARG_CAPTION:
	if (win->caption!=NULL)
	    free(win->caption);
	if (arg->value!=NULL)
	    win->caption = strdup((char*)arg->value);
	else
	    win->caption = NULL;
	break;
	
     default:
	if (!W_ConfigureViewArg(win->view, arg)) {
	    wWarning("bad argument value %i in configureWindow",
		     arg->argument);
	    return False;
	}
    }
    return True;
}


int
WMConfigureWindow(WMWindow *wPtr, WMArgument *argv, int argc) 
{
    int i;
    
    CHECK_CLASS(wPtr, WC_Window);
    
    if (!wPtr->flags.configured) {
	for (i=0; i<sizeof(windowArguments)/sizeof(WMArgument); i++) {
	    if (!configureWindowArg(wPtr, &(windowArguments[i])))
		return False;
	}	
	wPtr->flags.configured = 1;
    }

    for (i=0; i<argc; i++) {
	if (!configureWindowArg(wPtr, &(argv[i])))
	    return False;
    }
    
    return True;
}


static void
destroyWindow(_Window *win)
{

    if (win->caption)
	free(win->caption);
    
    if (win->wclass)
	free(win->wclass);
    
    if (win->wname)
	free(win->wname);

    free(win);
}


