#include <Interviews\X11\windata.h>
#include <Interviews\X11\worldrep.h>
#include <Interviews\interactor.h>
#include <InterViews\world.h>
#include <Interviews\cursor.h>
#include <Interviews\color.h>
#include <Interviews\canvas.h>
#include <Interviews\bitmap.h>
#include <stdio.h>
#include <string.h>

extern "C" {
extern long FAR PASCAL IVWindowProc(HWND, unsigned int, WORD, LONG);
}

WindowData::WindowData () {
    hIcon = NULL;
}

WindowData::~WindowData () {
    if (hIcon != NULL) {
	DeleteObject(hIcon);
    }
}

HICON WindowData::MakeWndIcon (Bitmap* bits, Bitmap* mask) {
    unsigned iconmask[64];
    unsigned iconbits[64];

    DWORD BitmapDimension = (bits->Width()*bits->Height())/8;

    GetBitmapBits((HBITMAP)bits->Map(), BitmapDimension, (LPSTR)&iconbits);
    GetBitmapBits((HBITMAP)mask->Map(), BitmapDimension, (LPSTR)&iconmask);

    for (int i = 0; i < 64; i++) {
        iconbits[i] = ~iconbits[i];
        iconbits[i] = iconbits[i] & ~iconmask[i];
    }

    return CreateIcon (_world->hinstance(),
		       32,
		       32,
		       1, 1,
		       (LPSTR)iconmask,
		       (LPSTR)iconbits
		      );
}

HICON WindowData::GetWndIcon () {
    if ((ia->GetIconBitmap() != nil) && (ia->GetIconMask() != nil)) {
	hIcon = MakeWndIcon (ia->GetIconBitmap(), ia->GetIconMask());
	return hIcon;
    } else {
        return LoadIcon(NULL, IDI_APPLICATION);
    }
}

void* WindowData::GetWndClass () {
    if (ia->GetInteractorType() != InteriorInteractor) {
	WNDCLASS wndclass;

	sprintf(class_name, "%lX", this);
	do {
	    wndclass.style 	   = CS_HREDRAW | CS_VREDRAW;
	    wndclass.lpfnWndProc   = IVWindowProc;
	    wndclass.cbClsExtra    = 0;
	    wndclass.cbWndExtra    = 0;
	    wndclass.hInstance     = _world->hinstance();
	    wndclass.hIcon 	   = GetWndIcon();
	    wndclass.hCursor       = NULL;
	    wndclass.lpszClassName = class_name;
	    wndclass.hbrBackground = GetStockObject(WHITE_BRUSH);
	    wndclass.lpszMenuName  = NULL;
	}
	while (!RegisterClass(&wndclass));

    } else {
	strcpy(class_name, "IVChild");
    }

    return (void*)class_name;
}


const char* WindowData::GetWndName () {
    const char* title = ia->GetName();
    if (title == nil) {
	title = ia->GetInstance();
	if (title == nil) {
	    title = ia->GetWorld()->GetInstance();
	}
    }
    return title;
}

DWORD WindowData::GetWndStyle () {
    DWORD style = 0x0;
    InteractorType itype = ia->GetInteractorType();

    style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
    switch (itype) {
	case InteriorInteractor:
	    style |= WS_CHILDWINDOW;
	    break;
	case ApplicationInteractor:
	case ToplevelInteractor:
	    style |= WS_OVERLAPPEDWINDOW;
	    break;
	default:
	    style |= WS_POPUP;
	    break;
    }
    return style;
}
