// Indicator2Ctl.cpp : Implementation of the CIndicator2Ctrl ActiveX Control class.

#include "stdafx.h"
#include "Indicator2.h"
#include "Indicator2Ctl.h"
#include "Indicator2Ppg.h"

#include <math.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

const short DEGREE_CHAR = 176;

static const FONTDESC _fontdescHeading =
  { sizeof(FONTDESC), OLESTR("MS Sans Serif"), FONTSIZE( 12 ), FW_BOLD, 
     ANSI_CHARSET, FALSE, FALSE, FALSE };

IMPLEMENT_DYNCREATE(CIndicator2Ctrl, COleControl)


/////////////////////////////////////////////////////////////////////////////
// Message map

BEGIN_MESSAGE_MAP(CIndicator2Ctrl, COleControl)
	//{{AFX_MSG_MAP(CIndicator2Ctrl)
	// NOTE - ClassWizard will add and remove message map entries
	//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_MSG_MAP
	ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// Dispatch map

BEGIN_DISPATCH_MAP(CIndicator2Ctrl, COleControl)
	//{{AFX_DISPATCH_MAP(CIndicator2Ctrl)
	DISP_PROPERTY_NOTIFY(CIndicator2Ctrl, "Precision", m_precision, OnPrecisionChanged, VT_I2)
	DISP_PROPERTY_NOTIFY(CIndicator2Ctrl, "Units", m_units, OnUnitsChanged, VT_BSTR)
	DISP_PROPERTY_NOTIFY(CIndicator2Ctrl, "Type", m_type, OnTypeChanged, VT_I2)
	DISP_PROPERTY_NOTIFY(CIndicator2Ctrl, "IndicatorColor", m_indicatorColor, OnIndicatorColorChanged, VT_COLOR)
	DISP_PROPERTY_NOTIFY(CIndicator2Ctrl, "Alignment", m_alignment, OnAlignmentChanged, VT_I2)
	DISP_PROPERTY_NOTIFY(CIndicator2Ctrl, "Horizontal", m_horizontal, OnHorizontalChanged, VT_I2)
	DISP_PROPERTY_EX(CIndicator2Ctrl, "Value", GetValue, SetValue, VT_R8)
	DISP_PROPERTY_EX(CIndicator2Ctrl, "HeadingFont", GetHeadingFont, SetHeadingFont, VT_FONT)
	DISP_STOCKPROP_BACKCOLOR()
	DISP_STOCKPROP_CAPTION()
	DISP_STOCKPROP_FONT()
	DISP_STOCKPROP_FORECOLOR()
	//}}AFX_DISPATCH_MAP
	DISP_FUNCTION_ID(CIndicator2Ctrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE)
END_DISPATCH_MAP()


/////////////////////////////////////////////////////////////////////////////
// Event map

BEGIN_EVENT_MAP(CIndicator2Ctrl, COleControl)
	//{{AFX_EVENT_MAP(CIndicator2Ctrl)
	// NOTE - ClassWizard will add and remove event map entries
	//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_EVENT_MAP
END_EVENT_MAP()


/////////////////////////////////////////////////////////////////////////////
// Property pages

// TODO: Add more property pages as needed.  Remember to increase the count!
BEGIN_PROPPAGEIDS(CIndicator2Ctrl, 3)
	PROPPAGEID(CIndicator2PropPage::guid)
    PROPPAGEID(CLSID_CColorPropPage)
    PROPPAGEID(CLSID_CFontPropPage)
END_PROPPAGEIDS(CIndicator2Ctrl)


/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid

IMPLEMENT_OLECREATE_EX(CIndicator2Ctrl, "INDICATOR2.Indicator2Ctrl.1",
	0xaddfd756, 0x383f, 0x4f7d, 0x98, 0xb4, 0x36, 0x42, 0xe, 0xc4, 0xa7, 0xff)


/////////////////////////////////////////////////////////////////////////////
// Type library ID and version

IMPLEMENT_OLETYPELIB(CIndicator2Ctrl, _tlid, _wVerMajor, _wVerMinor)


/////////////////////////////////////////////////////////////////////////////
// Interface IDs

const IID BASED_CODE IID_DIndicator2 =
		{ 0x25fecf69, 0xad09, 0x46b3, { 0xaa, 0xcb, 0x1e, 0x28, 0xbd, 0x8a, 0x23, 0x90 } };
const IID BASED_CODE IID_DIndicator2Events =
		{ 0x54c9e680, 0x97d5, 0x48db, { 0x9d, 0x10, 0x85, 0x4, 0x6f, 0x66, 0xa8, 0x57 } };


/////////////////////////////////////////////////////////////////////////////
// Control type information

static const DWORD BASED_CODE _dwIndicator2OleMisc =
	OLEMISC_ACTIVATEWHENVISIBLE |
	OLEMISC_SETCLIENTSITEFIRST |
	OLEMISC_INSIDEOUT |
	OLEMISC_CANTLINKINSIDE |
	OLEMISC_RECOMPOSEONRESIZE;

IMPLEMENT_OLECTLTYPE(CIndicator2Ctrl, IDS_INDICATOR2, _dwIndicator2OleMisc)


/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl::CIndicator2CtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for CIndicator2Ctrl

BOOL CIndicator2Ctrl::CIndicator2CtrlFactory::UpdateRegistry(BOOL bRegister)
{
	// TODO: Verify that your control follows apartment-model threading rules.
	// Refer to MFC TechNote 64 for more information.
	// If your control does not conform to the apartment-model rules, then
	// you must modify the code below, changing the 6th parameter from
	// afxRegApartmentThreading to 0.

	if (bRegister)
		return AfxOleRegisterControlClass(
			AfxGetInstanceHandle(),
			m_clsid,
			m_lpszProgID,
			IDS_INDICATOR2,
			IDB_INDICATOR2,
			afxRegApartmentThreading,
			_dwIndicator2OleMisc,
			_tlid,
			_wVerMajor,
			_wVerMinor);
	else
		return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}


/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl::CIndicator2Ctrl - Constructor

CIndicator2Ctrl::CIndicator2Ctrl() : m_fontHeading( &m_xFontNotification )
{
	InitializeIIDs(&IID_DIndicator2, &IID_DIndicator2Events);

	// TODO: Initialize your control's instance data here.
}


/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl::~CIndicator2Ctrl - Destructor

CIndicator2Ctrl::~CIndicator2Ctrl()
{
	// TODO: Cleanup your control's instance data here.
}

void CIndicator2Ctrl::OnDraw(CDC* pdc, const CRect& rcBounds,
							 const CRect& rcInvalid)
{
    // Create a compatible DC.
    HDC hdcMem = CreateCompatibleDC(pdc->GetSafeHdc());

    // Create a bitmap big enough for client rectangle.
    HBITMAP hbmMem = CreateCompatibleBitmap(pdc->GetSafeHdc(),
		rcBounds.right-rcBounds.left, rcBounds.bottom-rcBounds.top);

    // Select the bitmap into the off-screen DC.
    HBITMAP hbmOld = (HBITMAP) SelectObject(hdcMem, hbmMem);

    // Render the image into the offscreen DC.
	CDC *pdcm = CDC::FromHandle(hdcMem);
	MyOnDraw(pdcm,rcBounds,rcInvalid);

    // Blt the changes to the screen DC.
    BitBlt(pdc->GetSafeHdc(),rcBounds.left, rcBounds.top,
           rcBounds.right-rcBounds.left, rcBounds.bottom-rcBounds.top,
           hdcMem, 0, 0, SRCCOPY);

    // Done with off-screen bitmap and DC.
    SelectObject(hdcMem, hbmOld);
    DeleteObject(hbmMem);
    DeleteDC(hdcMem);
}

/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl::MyOnDraw - Drawing function

void CIndicator2Ctrl::MyOnDraw(
			CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
	CFont* pOldFont;
	CPoint points[3];
    TEXTMETRIC tm;
	char str[32];
	const CString& strCaption = InternalGetText();
    CBrush bkBrush(TranslateColor(GetBackColor()));

	// Set the ForeColor property color and transparent background mode into the device context
    pdc->SetTextColor(TranslateColor(GetForeColor()));
    pdc->SetBkMode(TRANSPARENT);

	// Paint the background using the BackColor property
    pdc->FillRect(rcBounds, &bkBrush);

	// Set the caption
	pOldFont = SelectStockFont(pdc);
    pdc->GetTextMetrics(&tm);

    // Draw the caption using the stock Font and ForeColor properties
	if (!m_horizontal) {
		pdc->SetTextAlign(TA_CENTER);
		pdc->ExtTextOut((rcBounds.left + rcBounds.right) / 2,rcBounds.top,
			ETO_CLIPPED, rcBounds, strCaption, strCaption.GetLength(), NULL);
	} else {
		pdc->SetTextAlign(TA_LEFT | TA_BOTTOM);
	    pdc->ExtTextOut(rcBounds.left,rcBounds.bottom,
			ETO_CLIPPED, rcBounds, strCaption, strCaption.GetLength(), NULL);
	}

	// Set the indicator font
	pdc->SetTextColor(m_indicatorColor);
	SelectFontObject(pdc, m_fontHeading);
	GetIndicatorString(str);
	switch (m_alignment) {
	case (-1):
		pdc->SetTextAlign(TA_LEFT | TA_BOTTOM);
		pdc->ExtTextOut(rcBounds.left,rcBounds.bottom,
			ETO_CLIPPED, rcBounds, str, strlen(str), NULL);		
		break;
	case (1):
		pdc->SetTextAlign(TA_RIGHT | TA_BOTTOM);
		pdc->ExtTextOut(rcBounds.right,rcBounds.bottom,
			ETO_CLIPPED, rcBounds, str, strlen(str), NULL);
		break;
	case (0):
	default:
		pdc->SetTextAlign(TA_CENTER | TA_BOTTOM);
		pdc->ExtTextOut((rcBounds.left + rcBounds.right) / 2,rcBounds.bottom,
			ETO_CLIPPED, rcBounds, str, strlen(str), NULL);
		break;
	}

	// Restore the device to its original state
	pdc->SelectObject(pOldFont);
}


/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl::DoPropExchange - Persistence support

void CIndicator2Ctrl::DoPropExchange(CPropExchange* pPX)
{
	ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
	COleControl::DoPropExchange(pPX);

	// TODO: Call PX_ functions for each persistent custom property.
	PX_Font(pPX, _T("HeadingFont"), m_fontHeading, &_fontdescHeading);
	PX_Color(pPX, _T("IndicatorColor"), m_indicatorColor, RGB(255,0,0));
	PX_Double(pPX, _T("Value"), m_value, 0.);
	PX_Short(pPX, _T("Precision"), m_precision, 2);
	PX_Short(pPX, _T("Type"), m_type, -1);
	PX_Short(pPX, _T("Alignment"), m_alignment, 1);
	PX_String(pPX, _T("Units"), m_units, "");
	PX_Short(pPX, _T("Horizontal"), m_horizontal, 1);

}

void CIndicator2Ctrl::GetIndicatorString(char *str)
{
	switch (m_type) {
	case (LatLongDD):
		GetDD(str);
		break;
	case (LatLongDDMM):
		GetDDMM(str);
		break;
	case (LatLongDDMMSS):
		GetDDMMSS(str);
		break;
	case (Temperature):
		GetTemperature(str);
		break;
	case (Angle):
		GetAngle(str);
		break;
	case (Time):
		GetTime(str);
		break;
	default:
		sprintf(str,"%.*f %s",m_precision,m_value,m_units);
		break;
	}
}

void CIndicator2Ctrl::GetDD(char *str)
{
	sprintf(str,"%.*f%c",m_precision,m_value,DEGREE_CHAR);
}

void CIndicator2Ctrl::GetDDMM(char *str)
{
	bool negative = m_value < 0.;
	double value = fabs(m_value);
	int deg = (int) floor(value);	
	double minutes = (value - deg)*60.;
	if (negative) deg *= -1;
	sprintf(str,"%d%c %.*f'",deg,DEGREE_CHAR,m_precision,minutes);
}

void CIndicator2Ctrl::GetDDMMSS(char *str)
{
	bool negative = m_value < 0.;
	double value = fabs(m_value);
	int deg = (int) floor(value);	
	double minutes = (value - deg)*60.;
	int min = (int) floor(minutes);
	double seconds = (value - deg - (double)min/60.)*3600.;
	if (negative) deg *= -1;
	sprintf(str,"%d%c %d' %.*f\"",deg,DEGREE_CHAR,min,m_precision,seconds);	
}

void CIndicator2Ctrl::GetTime(char *str)
{
	int hours = (int) floor(m_value/3600.);
	int minutes = (int) floor((m_value-(double)hours*3600.)/60.);
	double seconds = m_value-(double)hours*3600.-(double)minutes*60.;
	char *spacer1 = "";
	char *spacer2 = "";
	char *spacer3 = "";
	if (hours < 10) spacer1 = "0";
	if (minutes < 10) spacer2 = "0";
	if (seconds < 10.) spacer3 = "0";
	sprintf(str,"%s%d:%s%d:%s%.*f",spacer1,hours,spacer2,
		minutes,spacer3,m_precision,seconds);
}

void CIndicator2Ctrl::GetAngle(char *str)
{
	GetTemperature(str);
}

void CIndicator2Ctrl::GetTemperature(char *str)
{
	sprintf(str,"%.*f%c%s",m_precision,m_value,DEGREE_CHAR,m_units);
}

/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl::OnResetState - Reset control to default state

void CIndicator2Ctrl::OnResetState()
{
	COleControl::OnResetState();  // Resets defaults found in DoPropExchange

	// TODO: Reset any other control state here.
}


/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl::AboutBox - Display an "About" box to the user

void CIndicator2Ctrl::AboutBox()
{
	CDialog dlgAbout(IDD_ABOUTBOX_INDICATOR2);
	dlgAbout.DoModal();
}


/////////////////////////////////////////////////////////////////////////////
// CIndicator2Ctrl message handlers

double CIndicator2Ctrl::GetValue() 
{
	// TODO: Add your property handler here
	return m_value;
}

void CIndicator2Ctrl::SetValue(double newValue) 
{
	// TODO: Add your property handler here
	m_value = newValue;
    // force the control to redraw itself
    InvalidateControl();
	SetModifiedFlag();
}

void CIndicator2Ctrl::OnPrecisionChanged() 
{
	// TODO: Add notification handler code
    // force the control to redraw itself
    InvalidateControl();
	SetModifiedFlag();
}

void CIndicator2Ctrl::OnUnitsChanged() 
{
	// TODO: Add notification handler code
    // force the control to redraw itself
    InvalidateControl();
	SetModifiedFlag();
}

void CIndicator2Ctrl::OnTypeChanged() 
{
	// TODO: Add notification handler code
    // force the control to redraw itself
    InvalidateControl();
	SetModifiedFlag();
}

void CIndicator2Ctrl::OnIndicatorColorChanged() 
{
	// TODO: Add notification handler code
    // force the control to redraw itself
    InvalidateControl();
	SetModifiedFlag();
}

LPFONTDISP CIndicator2Ctrl::GetHeadingFont() 
{
	// TODO: Add your property handler here
	return m_fontHeading.GetFontDispatch( );
}

void CIndicator2Ctrl::SetHeadingFont(LPFONTDISP newValue) 
{
	// TODO: Add your property handler here
    m_fontHeading.InitializeFont( &_fontdescHeading, newValue);
    OnFontChanged();    //notify any changes
    SetModifiedFlag( );
}

void CIndicator2Ctrl::OnAlignmentChanged() 
{
	// TODO: Add notification handler code
    // force the control to redraw itself
    InvalidateControl();
	SetModifiedFlag();
}

void CIndicator2Ctrl::OnHorizontalChanged() 
{
	// TODO: Add notification handler code
    // force the control to redraw itself
    InvalidateControl();
	SetModifiedFlag();
}
