#include "stdafx.h"
#include "Viewer.h"
#include "resource.h"
#include "FrmWnd.h"
#include "imp_view.h"

HRESULT CViewer::CreateInstance(const IID &riid, void **ppv)
{
	CViewer* pObj; 
	pObj = new CViewer();
	if (pObj == NULL)
		return E_OUTOFMEMORY; 
	HRESULT hr; 
	if ( FAILED(hr = pObj->QueryInterface(riid, (void**)ppv))) 
		delete pObj ; 
	return hr;
}

CViewer::CViewer() : m_refcount(0), m_pFrmWnd(NULL), m_dwLayer(0)
{
}

CViewer::~CViewer()
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());
	
	if ( m_pFrmWnd && m_pFrmWnd->m_hWnd )
		m_pFrmWnd->DestroyWindow();
	if ( m_pFrmWnd )
		delete(m_pFrmWnd);
}

STDMETHODIMP CViewer::QueryInterface(const IID &riid, void **ppvObject)
{
	if ( riid == IID_IUnknown )
		*ppvObject = (IUnknown*)this;
	else if ( riid == IID_IViewer )
		*ppvObject = (IViewer*)this;
	else *ppvObject = NULL;
	if ( !*ppvObject )
		return E_NOINTERFACE;
	((IUnknown*)*ppvObject)->AddRef();
	return S_OK;
}

STDMETHODIMP_(ULONG) CViewer::AddRef()
{
	return InterlockedIncrement(&m_refcount);
}

STDMETHODIMP_(ULONG) CViewer::Release()
{
	if ( 0 == InterlockedDecrement(&m_refcount) )
	{
		delete(this);
		return 0;
	}
	return m_refcount;
}

STDMETHODIMP CViewer::SetData(LPVIEWERDATA pData)
{
	m_pData = pData;
	if ( pData->ppData )
		m_pFrmWnd->m_pData = pData;
	else
		m_pFrmWnd->m_pData = NULL;
	return S_OK;
}

STDMETHODIMP CViewer::ShowViewer(CDocument* pDocument, CWnd* pMainWnd)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());
	m_pWndMain = pMainWnd;
	if ( !m_pFrmWnd )
		m_pFrmWnd = (CFrmWnd*)CFrmWnd::CreateObject();
	if ( !m_pFrmWnd )
		return E_OUTOFMEMORY;
	if ( !m_pFrmWnd->m_hWnd )
	{
		m_pFrmWnd->Create(AfxRegisterWndClass(0, 0, (HBRUSH)(COLOR_BTNFACE + 1)), 
		L"View Plot", 
		WS_OVERLAPPEDWINDOW,
		CFrameWnd::rectDefault,
		NULL, 
		MAKEINTRESOURCE(IDR_MENU1));
		m_pFrmWnd->m_pViewerPtr = this;
		m_pDocument = pDocument;
	}
	m_pFrmWnd->ShowWindow(SW_SHOW);
	return S_OK;
}

STDMETHODIMP CViewer::Refresh(DWORD dwType)
{
	m_pFrmWnd->UpdateMenu();
	m_pFrmWnd->Update(dwType);

	return S_OK;
}

STDMETHODIMP CViewer::GetName(CString &rstrName)
{
	rstrName = L"VPlot";
	return S_OK;
}

STDMETHODIMP CViewer::GetDescription(CString &rstrDescription)
{
	rstrDescription = L"Unknown Description";
	return S_OK;
}