#include "StdAfx.h"
#include "MouseSnap.h"

CMouseSnap::CMouseSnap() : m_bSnapEnabled(true), m_bGridEnabled(true), m_nXOffset(0), m_nYOffset(0), m_rectActual(0), m_nSnapIncrement(10)
{
}

CMouseSnap::~CMouseSnap()
{
}

void CMouseSnap::EnableSnap(bool bEnable)
{
	m_bSnapEnabled = bEnable;
}

void CMouseSnap::SetSnapIncrement(int nNewSnapIncrement)
{
	m_nSnapIncrement = nNewSnapIncrement;
}

void CMouseSnap::SnapCursor(CPoint &point)
{
	if(!m_bSnapEnabled)
		return;

	if((point.x % m_nSnapIncrement) > 5)
		point.x = point.x - (point.x % m_nSnapIncrement) + m_nSnapIncrement;
	else
		point.x = point.x - (point.x % m_nSnapIncrement);
	if((point.y % m_nSnapIncrement) > 5)
		point.y = point.y - (point.y % m_nSnapIncrement) + m_nSnapIncrement;
	else
		point.y = point.y - (point.y % m_nSnapIncrement);
}

void CMouseSnap::DrawCursor(CDC *pDC, CPoint point)
{
	if(!m_bSnapEnabled)
		return;
	if(m_rectActual.PtInRect(point))
		return;

	int oldROP2(R2_COPYPEN);
	if(pDC != NULL)
		oldROP2 = pDC->SetROP2(R2_NOTXORPEN);

	CPoint tlp = point;
	SnapCursor(tlp);
	pDC->Rectangle(&m_rectActual);
	pDC->Rectangle(tlp.x, tlp.y, tlp.x+m_nSnapIncrement,tlp.y+m_nSnapIncrement);
	m_rectActual.SetRect(tlp.x, tlp.y, tlp.x+m_nSnapIncrement, tlp.y+m_nSnapIncrement);
	if (pDC != NULL)
		pDC->SetROP2(oldROP2);
}

void CMouseSnap::InitGrid(int nXRes, int nYRes)
{
	m_nXResolution = nXRes;
	m_nYResolution = nYRes;
}

void CMouseSnap::EnableGrid(bool bEnable)
{
	if(m_bGridEnabled)
		m_bGridEnabled = false;
	else m_bGridEnabled = true;
	//m_bGridEnabled = bEnable;
}

void CMouseSnap::DrawGrid(CDC *pDC)
{
	if(!m_bGridEnabled)
		return;
	CPen PenThick, PenThin;
	PenThin.CreatePen(PS_COSMETIC | PS_SOLID, 1, COLORREF(RGB(200,250,200)));
	PenThick.CreatePen(PS_COSMETIC | PS_SOLID, 1, COLORREF(RGB(160, 210, 160)));

	pDC->SelectObject(&PenThin);

	for(int j=5; j<m_nYResolution; j+=m_nSnapIncrement){
		pDC->MoveTo(0, j);
		pDC->LineTo(m_nYResolution, j);
	}
	for(int i=5; i<m_nXResolution; i+=m_nSnapIncrement){
		pDC->MoveTo(i, 0);
		pDC->LineTo(i, m_nXResolution);
	}
	pDC->SelectObject(&PenThick);
	for(int j=5; j<m_nYResolution; j+=(m_nSnapIncrement*10)){
		pDC->MoveTo(0, j);
		pDC->LineTo(m_nYResolution, j);
	}
	for(int i=5; i<m_nXResolution; i+=(m_nSnapIncrement*10)){
		pDC->MoveTo(i, 0);
		pDC->LineTo(i, m_nXResolution);
	}
}