#include <GDI.h>
#include <bitbutton.h>

BitButton::BitButton()
    : Win32xx::CWnd(), bmpAlpha(255), bNormal(0), bActive(0), bDisabled(0)
{
}

BitButton::~BitButton()
{
    if (bNormal)
        delete bNormal;
    if (bActive)
        delete bActive;
    if (bDisabled)
        delete bDisabled;
}

void BitButton::setNormalBitmap(HBITMAP bmp)
{
    if (bNormal)
        delete bNormal;
    bNormal = new Graphics::Bitmap(bmp);
    //InvalidateRect((LPRECT)GetClientRect(), FALSE);
}

void BitButton::setActiveBitmap(HBITMAP bmp)
{
    if (bActive)
        delete bActive;
    bActive = new Graphics::Bitmap(bmp);
    //InvalidateRect((LPRECT)GetClientRect(), FALSE);
}

void BitButton::setDisabledBitmap(HBITMAP bmp)
{
    if (bDisabled)
        delete bDisabled;
    bDisabled = new Graphics::Bitmap(bmp);
    //InvalidateRect((LPRECT)GetClientRect(), FALSE);
}

void BitButton::setAlpha(int alpha)
{
    bmpAlpha = alpha;
}

void BitButton::OnPaint(HDC dc)
{
    if (!bNormal || !bActive)
	return;
	
    CRect r = GetWindowRect();
    if (bmpAlpha == 255)
    {
        if (GetCapture() == GetHwnd())
            bActive->draw(dc);
        else
            bNormal->draw(dc);
    }
    else
    {
        Graphics::Bitmap bkg(*background, r.left, r.top, r.Width(), r.Height());
        bkg.getBits();
        Graphics::Bitmap* b = GetCapture() == GetHwnd() ? bActive : bNormal;
        bkg.blend(*b, 0, 0, bmpAlpha, *((int*)b->getBits()));
        bkg.drawBits(dc, 0, 0);
    }
}

void BitButton::OnMouseDown()
{
    SetCapture();
    //::InvalidateRect(m_hWndParent, (LPRECT)GetWindowRect(), FALSE);
    InvalidateRect((LPRECT)GetClientRect(), FALSE);
}

void BitButton::OnMouseUp()
{
    ReleaseCapture();
    //::InvalidateRect(m_hWndParent, (LPRECT)GetWindowRect(), FALSE);
    InvalidateRect((LPRECT)GetClientRect(), FALSE);
    ::SendMessage(m_hWndParent, WM_COMMAND, cmdId, 0);
}

void BitButton::OnMouseMove()
{
    if (GetCapture() == GetHwnd())
    {
        
    }
}

void BitButton::PreCreate(CREATESTRUCT &cs)
{
    cs.style = WS_CHILD | WS_VISIBLE;
    cs.dwExStyle |= WS_EX_TRANSPARENT;
    cs.lpszClass = _T("bitbutton");
}


LRESULT BitButton::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
	case WM_ERASEBKGND:
	    // do nothing
	    break;
        case WM_LBUTTONDOWN:
            OnMouseDown();
            break;

        case WM_MOUSEMOVE:
            OnMouseMove();
            break;

        case WM_LBUTTONUP:
            OnMouseUp();
            break;
    }

    return WndProcDefault(hwnd, uMsg, wParam, lParam);
}

