// LessonA19.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"

#include "Chart.h"
#if defined(_UNICODE) || defined(UNICODE)
#	pragma comment(lib,"CChartu.lib")
#else
#	pragma comment(lib,"CChart.lib")
#endif
using namespace NsCChart;

#define SQR(x) ((x)*(x))

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];								// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];								// The title bar text

// Foward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_LESSONA19, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow)) 
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_LESSONA19);

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage is only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 

	wcex.style			= CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, (LPCTSTR)IDI_LESSONA19);
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= (LPCSTR)IDC_LESSONA19;
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HANDLE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}


POINT	ptCenter = {80, 60};
long	Radius = 20;

bool	bSelected = false;
bool	bLighted = false;
COLORREF	crNorm = RGB(192, 128, 128);
COLORREF	crLighted = RGB(255, 128, 128);
COLORREF	crSelected = RGB(0, 128, 128);
COLORREF	crFill = RGB(192, 128, 128);

bool	bDraged = false;
POINT	ptOld, ptCenterOld;

bool	PointInCircle(POINT point, RECT plotRect)
{
	return SQR(point.x-ptCenter.x-plotRect.left)+SQR(point.y-ptCenter.y-plotRect.top)<=SQR(Radius);
}

class CSubChart : public CChart
{
	bool		OnLButtonDown( HWND hWnd, POINT point, UINT ctrlKey )
	{
		static bool bSelected_Old = false;
		bool needUpdate = CChart::OnLButtonDown(hWnd, point, ctrlKey);
		if(PointInCircle(point, GetLastPlotRect()))
		{
			bSelected = true;
			bDraged = true;
			ptOld = point;
			ptCenterOld = ptCenter;
			
			RECT plotRect = GetLastPlotRect();
			//SetCapture(hWnd);
			ClientToScreen(hWnd, (LPPOINT)&plotRect);
			ClientToScreen(hWnd, (LPPOINT)&plotRect+1);
			ClipCursor(&plotRect);
			needUpdate = true;
		}
		else
		{
			if(bSelected != bSelected_Old)needUpdate = true;
			bSelected = false;
			bSelected_Old = bSelected;
		}
		return needUpdate;
	}
	bool		OnLButtonUp( HWND hWnd, POINT point, UINT ctrlKey )
	{
		bool needUpdate = false;
		if(bDraged)
		{
			bDraged = false;
			needUpdate = true;
		}

		return CChart::OnLButtonUp(hWnd, point, ctrlKey) | needUpdate;
	}
	bool		OnMouseMove( HWND hWnd, POINT point, UINT ctrlKey )
	{
		static bool bLighted_Old = false;
		bool needUpdate = false;
		if(bDraged)
		{
			ptCenter.x = ptCenterOld.x + (point.x - ptOld.x);
			ptCenter.y = ptCenterOld.y + (point.y - ptOld.y);

			RECT plotRect = GetLastPlotRect();
			if(ptCenter.x - Radius < 0)
				ptCenter.x += (Radius - ptCenter.x);
			if(ptCenter.x + Radius > plotRect.right - plotRect.left)
				ptCenter.x -= (ptCenter.x + Radius - plotRect.right + plotRect.left);
			if(ptCenter.y - Radius < 0)
				ptCenter.y += (Radius - ptCenter.y);
			if(ptCenter.y + Radius > plotRect.bottom - plotRect.top)
				ptCenter.y -= (ptCenter.y + Radius - plotRect.bottom + plotRect.top);

			needUpdate = true;
		}
		else
		{
			if(PointInCircle(point, GetLastPlotRect()))
			{
				bLighted = true;
			}
			else
			{
				bLighted = false;
			}
			if(bLighted!=bLighted_Old)needUpdate = true;
			bLighted_Old = bLighted;
		}
		
		return CChart::OnMouseMove(hWnd, point, ctrlKey) | needUpdate;
	}
	// 子类化键盘消息函数
	bool		OnKeyDown( HWND hWnd, UINT key )
	{
		MessageBox(NULL, _T("在子类里面哟！"), _T("提示"), MB_OK);
		
		//子类化消息处理函数时，应调用默认函数，否则消息处理将会混乱
		return CChart::OnKeyDown(hWnd, key);
	}
	
	//CChart里面有四个OnDraw函数，在CChartWnd中实际调用的是下面这个，故需要子类化它
	void		OnDraw(HWND hWnd)
	{
		//需要先调用默认函数，因为这个函数会清背景
		CChart::OnDraw(hWnd);
		
		RECT rtPlot = GetLastPlotRect();
		HDC hDC = GetDC(hWnd);
		//TCHAR str[] = _T("我现在是在子类中画图哟");
		//TextOut(hDC, rtPlot.left+10, rtPlot.top+10, str, _tcslen(str));
		HPEN hPen, hOldPen;
		HBRUSH hBrush, hOldBrush;
		COLORREF crLine;
		int linew = 2;;
		crLine = bSelected?crSelected:(bLighted?crLighted:crNorm);
		linew = bSelected?linew+2:(bLighted?linew+1:linew);
		hPen = CreatePen(PS_SOLID, linew, crLine);
		hOldPen = (HPEN)SelectObject(hDC, hPen);
		hBrush = CreateSolidBrush(crFill);
		hOldBrush = (HBRUSH)SelectObject(hDC, hBrush);

		Ellipse(hDC, rtPlot.left+ptCenter.x-Radius, rtPlot.top+ptCenter.y-Radius, rtPlot.left+ptCenter.x+Radius, rtPlot.top+ptCenter.y+Radius);

		SelectObject(hDC, hOldPen);
		DeleteObject(hPen);
		SelectObject(hDC, hOldBrush);
		DeleteObject(hBrush);
		ReleaseDC(hWnd, hDC);
	}
};

CSubChart *pSubChart = NULL;
CChart *pOldChart = NULL;

//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;
	TCHAR szHello[MAX_LOADSTRING];
	LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);

	static	CChartWnd chartWnd;

	switch (message) 
	{
		case WM_COMMAND:
			wmId    = LOWORD(wParam); 
			wmEvent = HIWORD(wParam); 
			// Parse the menu selections:
			switch (wmId)
			{
				case IDM_ABOUT:
				   DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
				   break;
				case IDM_EXIT:
				   DestroyWindow(hWnd);
				   break;
				default:
				   return DefWindowProc(hWnd, message, wParam, lParam);
			}
			break;
		case WM_CREATE:
			chartWnd.Attach(hWnd, kTypeXY);

			pSubChart = new CSubChart;
			pOldChart = chartWnd.SetChart(pSubChart);
			
			chartWnd.GetChart()->AddPoint2D(-3.0, 9.0);
			chartWnd.GetChart()->AddPoint2D(-2.0, 4.0);
			chartWnd.GetChart()->AddPoint2D(-1.0, 1.0);
			chartWnd.GetChart()->AddPoint2D(0.0, 0.0);
			chartWnd.GetChart()->AddPoint2D(1.0, 1.0);
			chartWnd.GetChart()->AddPoint2D(2.0, 4.0);
			chartWnd.GetChart()->AddPoint2D(3.0, 9.0);
			
			chartWnd.GetChart()->SetTitle(_T("Hello World，我的第一个CChart程序！"));

			break;
		case WM_PAINT:
			hdc = BeginPaint(hWnd, &ps);
			// TODO: Add any drawing code here...
			RECT rt;
			GetClientRect(hWnd, &rt);
			DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER);
			EndPaint(hWnd, &ps);
			break;
		case WM_DESTROY:
			chartWnd.SetChart(pOldChart);
			if(pSubChart)delete pSubChart;

			chartWnd.Detach();

			PostQuitMessage(0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}

// Mesage handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
		case WM_INITDIALOG:
				return TRUE;

		case WM_COMMAND:
			if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) 
			{
				EndDialog(hDlg, LOWORD(wParam));
				return TRUE;
			}
			break;
	}
    return FALSE;
}
