// HoloKotePreview.cpp : implementation file
//

#include "stdafx.h"
#include <atlimage.h>
#include "MainSheet.h"
#include "DTC_C++Demo.h"
#include "HoloKotePreview.h"
#include "afxdialogex.h"

////#############################################################################

// CHoloKotePreview dialog
IMPLEMENT_DYNAMIC(CHoloKotePreview, CDialog)

CHoloKotePreview::CHoloKotePreview(char *pBuff, 
								   int   slotCount,
								   CWnd* pParent /*=NULL*/)
	: CDialog(CHoloKotePreview::IDD, pParent)
{
	m_pBuff     = pBuff;
	m_slotcount = slotCount;
}

CHoloKotePreview::~CHoloKotePreview()
{
}

void CHoloKotePreview::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_SLOTNUMBER, m_SlotNumber);
	DDX_Control(pDX, IDC_PREVIEW, ctlBmp);
}

BEGIN_MESSAGE_MAP(CHoloKotePreview, CDialog)
	ON_CBN_SELCHANGE(IDC_SLOTNUMBER, &CHoloKotePreview::OnCbnSelchangeSlotnumber)
END_MESSAGE_MAP()


//#############################################################################

// CHoloKotePreview message handlers
BOOL CHoloKotePreview::OnInitDialog()
{
	CDialog::OnInitDialog();

	CString temp;
	for (int i = 1; i <= m_slotcount; i++)
	{
		temp.Format(_T("%d"), i);
		m_SlotNumber.AddString(temp);
	}
	m_SlotNumber.SetCurSel(0);
	DisplayBitmap(0);

	return false;
}

//*****************************************************************************

void CHoloKotePreview::OnCbnSelchangeSlotnumber()
{
	DisplayBitmap(m_SlotNumber.GetCurSel());
}

//#############################################################################

void CHoloKotePreview::DisplayBitmap
(
	int slot	//HoloKote Slot number
)
{
	int nWide = ID_HKPREVIEW_WIDTH;
	int nHigh = ID_HKPREVIEW_HEIGHT;
 
 	int nDwordsPerLine = (nWide + 31) / 32;   // rounds up to complete 32 bit DWORDS for each line
	int nBytesPerLine  = nDwordsPerLine * 4;
	int nPixelsPerLine = nBytesPerLine  * 8;
 
    //Expand the image to ensure that each line is padded to a round 32 bit (DWORD) length
	int nDataLen = nBytesPerLine * nHigh;
 	BYTE* pabBits = new BYTE[nDataLen];
	memset(pabBits, 0xff, nDataLen);

	//Calculate the offset to the required HoloKote slot
	int offset = slot * (ID_HKPREVIEW_SIZE + ID_HKKEYLEN);
	offset    += ID_HKKEYLEN; // Then offset past the key for this slot
	
	//Expand the bitmap so that each line is padded to 32 bit DWORD boundaries;
	for (int y = 0; y < nHigh; ++y) 
	{
        for (int x = 0; x < nWide; ++x) 
		{
            int bitIndex = x + y * nWide;
            bool set = ((m_pBuff[offset + (bitIndex / 8)] & (0x80 >> (bitIndex & 7))) != 0);

            BYTE mask = 0x80 >> (x % 8);
			if (set)
			{
				pabBits[(x / 8) + (y * nBytesPerLine)] |= mask;
			}
			else
			{
				pabBits[(x / 8) + (y * nBytesPerLine)] &= ~mask;
			}
        }
    }

	HBITMAP hBmp = ::CreateBitmap(nPixelsPerLine, nHigh, 1, 1, pabBits);
	ctlBmp.SetBitmap(hBmp);

	delete[] pabBits;
}
