#include <windows.h>
#include <tchar.h>
#include "resource.h"
#include "myapp.h"
#include "myappwin.h"
#include "myplain.h"
#include "mydjpeg.h"
#include "mybmp.h"

extern mylib::CMyApp* g_pApp;

namespace mylib
{
CMyApp::CMyApp(HINSTANCE hInstance, HINSTANCE hPrevInstance)
{
	m_pDoc = 0;

	// Save the instance handle
	m_hInstance = hInstance;

	// Load the strings
	int nChar;
	nChar = LoadString(hInstance, IDS_MY_APPTITLE, m_szAppTitle, MAX_LOAD_STRING);
	m_szAppTitle[nChar] = 0;

	// Register the Window Class
	if(hPrevInstance == 0)
		CMyWin::Register(hInstance);
	ParseCommandLine();
}

CMyApp::~CMyApp()
{
	delete m_pDoc;
}

int
CMyApp::Run(int nCmdShow)
{
	// Create Window
	CMyAppWin appwin(m_szAppTitle);

	// Create the document
	if(m_DocName.size() > 0)
	{
		std::vector<TCHAR>::const_iterator p = m_DocName.begin();
		switch(ContentType(&*p))
		{
		case CMyContent::TEXT_PLAIN:
			m_pDoc = (CMyContent*)(new CMyPlain(&*p));
			break;
		case CMyContent::IMAGE_JPEG:
			m_pDoc = (CMyContent*)(new CMyDjpeg(&*p));
			break;
		case CMyContent::IMAGE_BMP:
			m_pDoc = (CMyContent*)(new CMyBMP(&*p));
			break;
		default:
			break;
		}
	}
	appwin.Show(nCmdShow);
	appwin.Update();

	POINT pt;
	pt.x = 0;
	pt.y = 0;
	SIZE sz;
	sz.cx = 1;
	sz.cy = 1;
	HDC hdc = appwin.GetDC();
	if(m_pDoc)
		sz = m_pDoc->Size(hdc);
	appwin.ReleaseDC(hdc);
	appwin.SetDrawSize(pt, sz);
	
	// Enter Message Loop
	MSG msg;
	while(GetMessage(&msg, 0, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return (int)msg.wParam;
}

BOOL
CMyApp::ParseCommandLine()
{
	const TCHAR* pCmdLine = GetCommandLine();
	if(pCmdLine == 0)
		return FALSE;

	// First argument (executable name)
	const TCHAR* p = pCmdLine;
	while(*p <= (TCHAR)' ')
	{
		if(*p == 0)
			return FALSE;
		++p;
	}
	TCHAR q = ' ';
	if((*p == '"') || (*p == '\''))
	{
		q = *p;
		++p;
	}
	while(*p != q)
	{
		if(*p == 0)
			return FALSE;
		++p;
	}
	++p;
	// Second argument
	while(*p <= (TCHAR)' ')
	{
		if(*p == 0)
			return FALSE;
		++p;
	}
	if((*p == '"') || (*p == '\''))
	{
		q = *p;
		++p;
	}
	std::vector<TCHAR> arg;
	while(*p != q)
	{
		if(*p == 0)
		{
			arg.push_back((TCHAR)0);
			m_DocName = arg;
			return TRUE;
		}
		arg.push_back(*p);
		++p;
	}
	arg.push_back((TCHAR)0);
	m_DocName = arg;
	return TRUE;
}

int
CMyApp::ContentType(const TCHAR* szName)
{
	int nType = CMyContent::TEXT_PLAIN;;
	int n = 0;
	while(szName[n] != 0)
		++n;
	if(n < 4)
		return nType;
	if(szName[n - 4] == '.')
	{
		if(((szName[n - 3] == 'b') || (szName[n - 3] == 'B')) &&
		  ((szName[n - 2] == 'm') || (szName[n - 2] == 'M')) &&
		  ((szName[n - 1] == 'p') || (szName[n - 1] == 'P')))
			nType = CMyContent::IMAGE_BMP;
		else if(((szName[n - 3] == 'j') || (szName[n - 3] == 'J')) &&
		  ((szName[n - 2] == 'p') || (szName[n - 2] == 'P')) &&
		  ((szName[n - 1] == 'g') || (szName[n - 1] == 'G')))
			nType = CMyContent::IMAGE_JPEG;
	}
	return nType;
}

}	// namespace mylib
