#include "CMyPicButton.h"
#include "resource.h"

IMPLEMENT_DYNAMIC(CMyPicButton, CDialog)

BEGIN_MESSAGE_MAP(CMyPicButton, CDialog)
	ON_WM_SIZE()
	ON_WM_PAINT()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_LBUTTONDBLCLK()
END_MESSAGE_MAP()

CMyPicButton::CMyPicButton(CWnd* pParent)
	: CDialog(IDD_CMYPICBUTTON, pParent)
{
}

CMyPicButton::~CMyPicButton()
{
	if (tas1.pTexture)
		tas1.pTexture->Release();
	if (tas1.pSRV)
		tas1.pSRV->Release();
	if (tas2.pTexture)
		tas2.pTexture->Release();
	if (tas2.pSRV)
		tas2.pSRV->Release();
}

void CMyPicButton::SetPic(UINT pic1, UINT pic2)
{
	if (tas1.pTexture)
	{
		tas1.pTexture->Release();
		tas1.pTexture = nullptr;
	}
	if (tas1.pSRV)
	{
		tas1.pSRV->Release();
		tas1.pSRV = nullptr;
	}
	if (tas2.pTexture)
	{
		tas2.pTexture->Release();
		tas2.pTexture = nullptr;
	}
	if (tas2.pSRV)
	{
		tas2.pSRV->Release();
		tas2.pSRV = nullptr;
	}
	LoadResourceTexture(&pRenderer, pic1, &tas1.pTexture, &tas1.pSRV);
	LoadResourceTexture(&pRenderer, pic2, &tas2.pTexture, &tas2.pSRV);
}

void CMyPicButton::Draw()
{
	pRenderer.RenderClear();
	auto pSRVDraw = buttonState ? tas2.pSRV : tas1.pSRV;
	if (!pSRVDraw)
		return;
	pRenderer.SetTPenDraw(pSRVDraw);
	pRenderer.AddRenderCopy();
	pRenderer.DrawRenderCopy();
	pRenderer.RenderPresent();
}

void CMyPicButton::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BOOL CMyPicButton::OnInitDialog()
{
	CDialog::OnInitDialog();
	pRenderer.Init(m_hWnd);
	return 0;
}

void CMyPicButton::OnSize(UINT nType, int cx, int cy)
{
	CDialog::OnSize(nType, cx, cy);
	pRenderer.OnSize(cx, cy, nType == SIZE_MINIMIZED);
}

void CMyPicButton::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	
	// 不为绘图消息调用 CDialog::OnPaint()
	Draw();
}

void CMyPicButton::OnLButtonDown(UINT nFlags, CPoint point)
{
	
	buttonState = true;
	Draw();
	CDialog::OnLButtonDown(nFlags, point);
	//往父窗口发送消息
	auto parent = GetParent();
	if (parent != nullptr)
		::SendMessageW(parent->m_hWnd, MYPICBUTTON_LBUTTONDOWN, (WPARAM)0, (LPARAM)0);
}


void CMyPicButton::OnLButtonUp(UINT nFlags, CPoint point)
{
	
	buttonState = false;
	Draw();
	CDialog::OnLButtonUp(nFlags, point);
	//往父窗口发送消息
	auto parent = GetParent();
	if (parent != nullptr)
		::SendMessageW(parent->m_hWnd, MYPICBUTTON_LBUTTONUP, (WPARAM)this, (LPARAM)0);
}

void CMyPicButton::OnLButtonDblClk(UINT nFlags, CPoint point)
{
	
	OnLButtonDown(nFlags, point);
	CDialog::OnLButtonDblClk(nFlags, point);
}
