
#include "CMameWindow.h"
#include "CMameView_8Bit.h"

#include <Application.h>
#include <Bitmap.h>
#include <Screen.h>
#include <stdio.h>
#include <string.h>

CMameWindow::CMameWindow(
	status_t		*outRet,
	BRect			inFrame,
	int				inColorDepth) : BWindow(inFrame, "MAME", B_TITLED_WINDOW, B_NOT_ZOOMABLE | B_NOT_RESIZABLE)
{
	BScreen		theScreen;
	BRect		screenFrame = theScreen.Frame();

	MoveTo((screenFrame.Width()-inFrame.Width())/2, (screenFrame.Height()-inFrame.Height())/2);
	InitPalette();
	AddChild(mView = new CMameView_8Bit(Bounds()));
	mView->MakeFocus();

	mRequestedSize = inFrame;

	Show();
}

CMameWindow::~CMameWindow()
{
}

bool
CMameWindow::QuitRequested()
{
	Hide();
	WaitToQuit();
	
	return true;
}
void
CMameWindow::ShutDown()
{
	PostMessage(B_QUIT_REQUESTED);
}

void
CMameWindow::SetPenAtIdx(
	int32			inIdx,
	uint8			inRed,
	uint8			inGreen,
	uint8			inBlue)
{
	BScreen		theScreen(this);
	
	mPalette[inIdx].red = inRed;
	mPalette[inIdx].green = inGreen;
	mPalette[inIdx].blue = inBlue;
	mPenIndex[inIdx] = theScreen.IndexForColor(mPalette[inIdx]);
}

void
CMameWindow::SetPalette()
{
}

void
CMameWindow::InitPalette()
{
	BScreen	theScreen(this);
	int32	i;
		
	for (i=0;i<256; i++) {
		mPalette[i] = theScreen.ColorForIndex(i);
		mPenIndex[i] = i;
	}
}

void
CMameWindow::Update8BitDirect(
	uint8			*inSource,
	int32			inLineNumber,
	int32			inScreenWidth,
	int32			inVisibleWidth,
	bool			inDouble)
{
	// Fill in values for vector games...
	if (inVisibleWidth == 0) {
		inVisibleWidth = mRequestedSize.right + 1;
	}
	if (inScreenWidth == 0) {
		inScreenWidth = mRequestedSize.right + 1;
	}

	inScreenWidth += 16;

	BBitmap		*dstBitmap = mView->Bitmap();
	uint8		*pen = &mPenIndex[0];
	int32		dwidth = (inScreenWidth-16)>>2;
	int32		qwidth = inScreenWidth>>2;
	int32		pwidth = dstBitmap->BytesPerRow() >> 2;
	int32		i;
	uint32		*p, *q, *p2;
	uint8		*q2;

	if (inScreenWidth % 4)
		qwidth = ((inScreenWidth+4)& ~7)>>2;
		
	p = (uint32 *)mView->Bitmap()->Bits();
	q = (uint32 *)inSource;

	for (i=0;i<inLineNumber;i++) {
		p2=p;
		p=p+pwidth;
		q2=(uint8*)q;
		q=q+qwidth;


		for(int y=0;y<dwidth;y++) {
#ifdef B_HOST_IS_BENDIAN
			*p2++=(*(pen + *q2) << 24) | (*(pen + *(q2 + 1)) << 16) | (*(pen + *(q2 + 2)) << 8) | *(pen + *(q2 + 3));
#else
			*p2++=(*(pen + *(q2 + 3)) << 24) | (*(pen + *(q2 + 2)) << 16) | (*(pen + *(q2 + 1)) << 8) | *(pen + *(q2 + 0));
#endif
			q2 += 4;
		}
	}

	mView->Refresh();
}
	
void
CMameWindow::Update8BitDirectWScan(
	uint8			*inSource,
	int32			inLineNumber,
	int32			inScreenWidth,
	int32			inVisibleWidth)
{
}
