#include "stdafx.h"
#include "SChartWnd.h"

#include <time.h>
#include <math.h>
 
namespace SOUI
{
	SChartWnd::SChartWnd()
	{
		m_bFocusable = TRUE;

		bRun = false;
	}
 
 
	SChartWnd::~SChartWnd()
	{
	}
 
	void SChartWnd::OnPaint(IRenderTarget *pRT)
	{
		CRect rect;
		GetClientRect(&rect);

		HDC hDC = pRT->GetDC();
		chart.OnDraw(hDC, rect);
		pRT->ReleaseDC(hDC);
	}

	void SChartWnd::OnTimer(UINT_PTR nIDEvent)
	{
		if(1 != nIDEvent)return;

		static int nCnt = 0;
		static int nLen = 360;
		static double pi = 4.0*atan(1.0);

		double x, y;

		x = nCnt/100.0;
		y = 4.0*sin(2.0*pi*nCnt/nLen) + (2.0*rand()/RAND_MAX-1.0);

		chart.AddPoint2D(x, y);
		
		nCnt++;

		Invalidate();
	}

	int SChartWnd::OnCreate(LPVOID lpVoid)
	{
		SetFocus();
		chart.SetType(kTypeXY);
		chart.SetTitle(_T("实时曲线"));
		chart.SetBkgndColor(RGB(228, 228, 228));
		chart.AddCurve();
		chart.SetDataTitle(_T("实验数据"), 0);
		chart.SetXFloatTicks(true);
		chart.SetDataMaxPoints(1080, 0);
		chart.SetReservedMarginRight(10);
		chart.SetGridLine(true, true, true, true);
		chart.SetYRangeByInterval(true);
		chart.SetYTicksInterval(1.0);

		//SetTimer(1, 20);
		srand( (unsigned)time( NULL ) );
		return 0;
	}

	void SChartWnd::OnDestroy()
	{
		if(bRun)KillTimer(1);
	}

	UINT SChartWnd::OnGetDlgCode()
	{
		return (SC_WANTALLKEYS|SC_WANTSYSKEY);
	}

	void SChartWnd::OnLButtonDown(UINT nFlags,CPoint pt)
	{
		//__super::OnLButtonDown(nFlags, pt);
		//GetContainer()->OnSetSwndFocus(m_swnd);
		SetFocus();

		if(!bRun)
		{
			SetTimer(1, 20);
		}
		else
		{
			KillTimer(1);
		}
		bRun = !bRun;

		HWND hWnd = GetContainer()->GetHostHwnd();
		if(hWnd)
		{
			if(chart.OnLButtonDown(hWnd, pt, nFlags))
			{
				Invalidate();
			}
		}
		
	}

	void SChartWnd::OnLButtonUp(UINT nFlags,CPoint pt)
	{
		HWND hWnd = GetContainer()->GetHostHwnd();
		if(hWnd)
		{
			if(chart.OnLButtonUp(hWnd, pt, nFlags))
			{
				Invalidate();
			}
		}
	}
	void SChartWnd::OnLButtonDbClick(UINT nFlags,CPoint pt)
	{
		HWND hWnd = GetContainer()->GetHostHwnd();
		if(hWnd)
		{
			if(chart.OnLButtonDblClk(hWnd, pt, nFlags))
			{
				Invalidate();
			}
		}
	}

	void SChartWnd::OnMouseMove(UINT nFlags,CPoint pt)
	{
		HWND hWnd = GetContainer()->GetHostHwnd();
		if(hWnd)
		{
			if(chart.OnMouseMove(hWnd, pt, nFlags))
			{
				Invalidate();
			}
		}
	}

	void SChartWnd::OnRButtonDown(UINT nFlags,CPoint pt)
	{
		HWND hWnd = GetContainer()->GetHostHwnd();
		if(hWnd)
		{
			::ClientToScreen(hWnd, &pt);
			if(chart.OnContextMenu(NULL, hWnd, pt))
			{
				Invalidate();
			}
		}
	}
	
	void SChartWnd::OnKeyDown( UINT nChar, UINT nRepCnt, UINT nFlags )
	{
		HWND hWnd = GetContainer()->GetHostHwnd();
		SLOG_INFO("SChartWnd::OnKeyDown");
		if(hWnd)
		{
			if(chart.OnKeyDown(hWnd, nChar))
			{
				Invalidate();
			}
		}
	}
}
