
#include<windows.h>
#include"vismod.h"

#include"resource.h"

VisModule visMod;

HBRUSH hbrBarCol,hbrBack,hbrBorder;

int _nLevel=0;

void DrawLevels(HDC hdc,HWND hwndDlg)
{
	RECT rect;
	GetClientRect(hwndDlg,&rect);
	int widht=rect.right-rect.left;
	int height=rect.bottom-rect.top;

	// double buffering
	HDC hDCMem = CreateCompatibleDC(hdc); 
	HBITMAP hBitmap=CreateCompatibleBitmap(hdc,widht,height);
	HGDIOBJ hOldBitmap = SelectObject(hDCMem, hBitmap);

	FillRect(hDCMem,&rect,hbrBack);

	int barWidht=(int)((widht/(float)100)*_nLevel);
	rect.right=rect.left+barWidht;
	FillRect(hDCMem,&rect,hbrBarCol);


	GetClientRect(hwndDlg,&rect);
	FrameRect(hDCMem,&rect,hbrBorder);

	for(int i=0;i<50;i++)
	{
		rect.left+=2;
		FrameRect(hDCMem,&rect,hbrBorder);
	}

	BitBlt(hdc,0,0,widht,height,hDCMem,0,0,SRCCOPY);

	SelectObject(hDCMem, hOldBitmap);
	DeleteDC(hDCMem);
	DeleteObject(hBitmap);
}

void OnPaint(HWND hwndDlg)
{
	PAINTSTRUCT ps;

	HDC hdc=BeginPaint(hwndDlg,&ps);

	DrawLevels(hdc,hwndDlg);

	EndPaint(hwndDlg,&ps);
}

void OnPaintTimer(HWND hwndDlg)
{

	HDC hdc=GetDC(hwndDlg);

	DrawLevels(hdc,hwndDlg);

	ReleaseDC(hwndDlg,hdc);
}

void InitVisMod()
{
	visMod.hVisDlg=CreateDialog(visMod.hDllInstance,MAKEINTRESOURCE(IDD_DIALOG1),0,visMod.MainDlgProc);
	ShowWindow(visMod.hVisDlg,SW_SHOW);
}

BOOL VisDlgProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) // handle window messages!
{
	switch (msg) {
		case WM_INITDIALOG:
			{
				hbrBarCol=CreateSolidBrush(RGB(147,230,253));
				hbrBack=CreateSolidBrush(RGB(0,0,0));
				hbrBorder=CreateSolidBrush(RGB(0,0,0));

				SetTimer(hwnd,1002,20,0);

				SetWindowPos(hwnd,HWND_TOPMOST,0,0,100,10,SWP_NOMOVE);
			}
			break;
		case WM_PAINT:
			OnPaint(hwnd);
			break;
		case WM_TIMER:
			if(wParam==1002)
			{
				OnPaintTimer(hwnd);
				return TRUE;
			}else
			{
				return FALSE;
			}
		case WM_DESTROY:
			DeleteObject(hbrBarCol);
			DeleteObject(hbrBack);
			DeleteObject(hbrBorder);
			return TRUE;
		default:
			return FALSE;

		}

	return TRUE;
}

void ReadAudioSamples(LPWAVEHDR pWaveHdr,int nLevel,int bpm)
{
	_nLevel=nLevel;
}

void Quit()
{
	KillTimer(visMod.hVisDlg,1002);
}

extern "C" __declspec(dllexport) VisModule* GetVisMod()
{
	visMod.InitVisMod=InitVisMod;
	visMod.VisDlgProc=VisDlgProc;
	visMod.ReadAudioSamples=ReadAudioSamples;
	visMod.Quit=Quit;

	return &visMod;
}