#include "CBrushPreview.h"
#include "resource.h"

IMPLEMENT_DYNAMIC(CBrushPreview, CDialog)

BEGIN_MESSAGE_MAP(CBrushPreview, CDialog)
	ON_WM_SIZE()
	ON_WM_SHOWWINDOW()
	ON_WM_PAINT()
END_MESSAGE_MAP()

CBrushPreview::CBrushPreview(CWnd* pParent)
	: CDialog(IDD_CBRUSHPREVIEW, pParent)
{
}

CBrushPreview::~CBrushPreview()
{
	if (tas.pSRV)
		tas.pSRV->Release();
	if (tas.pTexture)
		tas.pTexture->Release();
	if (tas_nullpxa.pSRV)
		tas_nullpxa.pSRV->Release();
	if (tas_nullpxa.pTexture)
		tas_nullpxa.pTexture->Release();
}

void CBrushPreview::Draw()
{
	pRenderer.RenderClear();
	if (tas.pSRV)
	{
		CRect rc;
		GetWindowRect(&rc);
		MyRect src, dst ,adjustRc;

		dst.Set1(0, 0, (float)rc.Width(), (float)rc.Height());
		src.Set1(
			pBrushView->cursorX_selected * pBrushView->grid_w,
			pBrushView->cursorY_selected * pBrushView->grid_h, 
			pBrushView->cursorW_selected * pBrushView->grid_w,
			pBrushView->cursorH_selected * pBrushView->grid_h);
		adjustRc = src;
		adjustRc.AdjustIn(dst);
		pRenderer.SetTPenDraw(tas.pSRV);
		pRenderer.AddRenderCopy(&src, &adjustRc);
		pRenderer.DrawRenderCopy();
	}
	pRenderer.RenderPresent();
}

void CBrushPreview::Load(CString pxaName)
{
	if (loadedPxaName.GetLength() != 0 &&
		tas.pTexture &&
		tas.pSRV &&
		loadedPxaName == pxaName)
		return;//不重新载入贴图，直接跳过
	loadedPxaName = pxaName;
	CString pngName;
	pngName.Format(L"./data/pxa/%s.png", pxaName.GetString());
	//载入贴图
	if (tas.pSRV &&
		tas.pSRV != tas_nullpxa.pSRV)
	{
		tas.pSRV->Release();
		tas.pSRV = nullptr;
	}
	if (tas.pTexture &&
		tas.pTexture != tas_nullpxa.pTexture)
	{
		tas.pTexture->Release();
		tas.pTexture = nullptr;
	}
	std::vector<char> pngName_utf8;
	UTF16ToUTF8(pngName.GetString(), &pngName_utf8);
	//确认文件是否存在
	FILE* fp;
	fopen_s(&fp, pngName_utf8.data(), "rb");
	if (fp)
	{
		fclose(fp);
		//文件存在
		pRenderer.MyLoadTexture(&tas.pTexture, pngName_utf8.data());
		pRenderer.MyCreateShaderResourceView(&tas.pSRV, tas.pTexture);
	}
	else
	{
		//文件不存在
		tas = tas_nullpxa;
	}
}

void CBrushPreview::ResetContext()
{
	RefreshImage();
	Draw();
}

void CBrushPreview::RefreshImage()
{
	if (tas.pSRV &&
		tas.pSRV != tas_nullpxa.pSRV)
	{
		tas.pSRV->Release();
		tas.pSRV = nullptr;
	}
	if (tas.pTexture &&
		tas.pTexture != tas_nullpxa.pTexture)
	{
		tas.pTexture->Release();
		tas.pTexture = nullptr;
	}
}

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

BOOL CBrushPreview::OnInitDialog()
{
	CDialog::OnInitDialog();
	pRenderer.Init(m_hWnd);
	//载入资源
	LoadResourceTexture(&pRenderer, IDB_NULLPXA, &tas_nullpxa.pTexture, &tas_nullpxa.pSRV);
	return 0;
}

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

void CBrushPreview::OnShowWindow(BOOL bShow, UINT nStatus)
{
	CDialog::OnShowWindow(bShow, nStatus);
}

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