#include "StdAfx.h"
#include "XmlConverter.h"
#include "XmlConverterDlg.h"

#import "msxml3.dll"
using namespace MSXML2;
#include <string>
using namespace std;



/*--------------------------------------------------------------------------*/

void ConvertXMLStringToRTF
(
	wstring&             p_rwsText,
	CString&             p_rsOutput,
	const UINT           p_unCodePage
)
{
#define LBUF 30

	wstring              wsTmp;
	char                 szBuf[LBUF];
	CString              csFmt;
	int                  nLen;


	p_rsOutput = "";

	for ( int i=0; i<p_rwsText.length(); i++ )
	{
		wsTmp = p_rwsText.at(i);

		if ( wsTmp[0] < 128 )
		{
			// ASCII: we can cast
			switch ( wsTmp[0] )
			{
				case L'\\':
					p_rsOutput += "\\\\";
					continue;

				case L'{':
					p_rsOutput += "\\{";
					continue;

				case L'}':
					p_rsOutput += "\\}";
					continue;

				default:
					p_rsOutput += (char)wsTmp[0];
					continue;
			}
		}

		// Else: non-ASCII
		WideCharToMultiByte(p_unCodePage, 0,
			(LPCWSTR)wsTmp.c_str(), 2, 
			(LPSTR)szBuf, LBUF, NULL, NULL);

		if ( (nLen = strlen(szBuf)) < 2 )
		{
			// One byte
			csFmt.Format("\\u%d \\'%x", wsTmp[0], (unsigned char)szBuf[0]);
			p_rsOutput += csFmt;
		}
		else
		{
			// More than one byte
			csFmt.Format("{\\uc%d\\u%d", nLen, wsTmp[0]);
			p_rsOutput += csFmt;
			for ( int j=0; j<nLen; j++ )
			{
				csFmt.Format("\\'%x", (unsigned char)szBuf[j]);
				p_rsOutput += csFmt;
			}
			p_rsOutput += "}";
		}
			
	}

#undef LBUF
}



/*--------------------------------------------------------------------------*/

void ConvertXMLStringToFlash
(
	wstring&             p_rwsText,
	CString&             p_rsOutput,
	const UINT           p_unCodePage,
	const BOOL           p_bStrict
)
{
#define LBUF 30

	wstring              wsTmp;
	char                 szBuf[LBUF];
	CString              csFmt;
	int                  nLen;

	p_rsOutput = "";

	for ( int i=0; i<p_rwsText.length(); i++ )
	{
		wsTmp = p_rwsText.at(i);
		if ( wsTmp[0] < 128 )
		{
			// ASCII: we can cast
			switch ( wsTmp[0] )
			{
				case L' ':
					if ( p_bStrict ) p_rsOutput += '+';
					else p_rsOutput += ' ';
					continue;

				case L'+':
				case L'/':
				case L'?':
				case L'%':
				case L'&':
				case L'*':
					csFmt.Format("%%%x", (char)wsTmp[0]);
					p_rsOutput += csFmt;
					continue;

				default:
					if ( wsTmp[0] < 32 )
					{
						// Control characters
						csFmt.Format("%%%x", (char)wsTmp[0]);
						p_rsOutput += csFmt;
						continue;
					}

					p_rsOutput += (char)wsTmp[0];
					continue;
			}
		}

		// Else: non-ASCII
		WideCharToMultiByte(p_unCodePage, 0, (LPCWSTR)wsTmp.c_str(), 2, 
			(LPSTR)szBuf, LBUF, NULL, NULL);

		nLen = strlen(szBuf);
		for ( int j=0; j<nLen; j++ )
		{
			if ( p_bStrict )
			{
				csFmt.Format("%%%x", (unsigned char)szBuf[j]);
				p_rsOutput += csFmt;
			}
			else
			{
				if ( szBuf[j] < 128 )
				{
					// ASCII-like bytes
					switch ( szBuf[j] )
					{
						case L'+':
						case L'/':
						case L'?':
						case L'%':
						case L'&':
						case L'*':
							csFmt.Format("%%%x", (char)szBuf[j]);
							p_rsOutput += csFmt;
							break;

						default:
							p_rsOutput += (char)szBuf[j];
							continue;
					}
				}
				else
				{
					csFmt.Format("%%%x", (unsigned char)szBuf[j]);
					p_rsOutput += csFmt;
				}
			}
		}
	}

#undef LBUF
}



/*--------------------------------------------------------------------------*/

inline void TESTHR(HRESULT _hr) 
   { if FAILED(_hr) throw(_hr); }



#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif



/*--------------------------------------------------------------------------*/

class CAboutDlg : public CDialog
{
public:

	CAboutDlg();

	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL


protected:

	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};



/*--------------------------------------------------------------------------*/

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}



/*--------------------------------------------------------------------------*/

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}



/*--------------------------------------------------------------------------*/

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()



/*--------------------------------------------------------------------------*/

CXmlConverterDlg::CXmlConverterDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CXmlConverterDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CXmlConverterDlg)
	//}}AFX_DATA_INIT

	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}



/*--------------------------------------------------------------------------*/

void CXmlConverterDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);

	//{{AFX_DATA_MAP(CXmlConverterDlg)
	DDX_Control(pDX, IDC_STRICT, m_chkStrictSyntax);
	DDX_Control(pDX, IDC_ENCODING, m_cbEncoding);
	DDX_Control(pDX, IDC_RTF, m_edRTF);
	DDX_Control(pDX, IDC_XML, m_edXML);
	//}}AFX_DATA_MAP
}



/*--------------------------------------------------------------------------*/

BEGIN_MESSAGE_MAP(CXmlConverterDlg, CDialog)
	//{{AFX_MSG_MAP(CXmlConverterDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_CONVERTRTF, OnConvertToRTF)
	ON_BN_CLICKED(IDC_CONVERTFLASH, OnConvertToFlash)
	ON_BN_CLICKED(IDC_VIEW, OnView)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()



/*--------------------------------------------------------------------------*/

BOOL CXmlConverterDlg::OnInitDialog()
{
	bool                      bValidate = true;
	CString                   csMsg;

	
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	// when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE); // Set big icon
	//	SetIcon(m_hIcon, FALSE); // Buggy code in MFC

	// Default encoding
	m_cbEncoding.SetCurSel(0);

	// Default text in the input box
	csMsg.LoadString(IDC_DEFAULTINPUT);
	m_edXML.SetWindowText(csMsg);
	m_edXML.SetSel(-1, 0);

	
	return TRUE;  // return TRUE  unless you set the focus to a control
}



/*--------------------------------------------------------------------------*/

void CXmlConverterDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}



/*--------------------------------------------------------------------------*/
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon.  For MFC applications using the document/view model,
// this is automatically done for you by the framework.

void CXmlConverterDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}



/*--------------------------------------------------------------------------*/
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.

HCURSOR CXmlConverterDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}



/*--------------------------------------------------------------------------*/

void CXmlConverterDlg::OnConvertToRTF() 
{
	CString              csOut;
	CString              csTmp;
	CString              csRtf;
	CString              csHeader;
	_bstr_t              bsText;
	BSTR                 bsTmp;
	wstring              wsText;
	wstring              wsTmp;
   _variant_t           varOut((bool)TRUE);
	IXMLDOMDocumentPtr   pDoc;
	IXMLDOMNodeListPtr   pNodeList;
	IXMLDOMNodePtr       pNode;
	UINT                 unCodePage = GetCodePage();
	
	csHeader =
	"{\\rtf1\\ansi\\ansicpg1252\\uc1\\deff0\\deflang1033{\\fonttbl"
	"{\\f0\\fswiss\\fcharset0\\fprq2 Arial Unicode MS Western;}"
	"{\\f1\\fswiss\\fcharset238\\fprq2 Arial Unicode MS CE;}"
	"{\\f2\\fswiss\\fcharset204\\fprq2 Arial Unicode MS Cyr;}"
	"{\\f3\\fswiss\\fcharset161\\fprq2 Arial Unicode MS Greek;}"
	"{\\f4\\fswiss\\fcharset162\\fprq2 Arial Unicode MS Tur;}"
	"{\\f5\\fbidi \\fswiss\\fcharset177\\fprq2 Arial Unicode MS (Hebrew);}}";


	m_edXML.GetWindowText(csTmp);

   try
	{
      TESTHR(CoInitialize(NULL)); 
      TESTHR(pDoc.CreateInstance("msxml2.domdocument"));

      varOut = pDoc->loadXML(_bstr_t(csTmp));
      if ((bool)varOut == FALSE)
		{
			throw(0);
		}
		csOut = csHeader;
		pNodeList = pDoc->getElementsByTagName("p");

		pNode = pNodeList->nextNode();
		while ( pNode != NULL )
		{
			TESTHR(pNode->get_text(&bsTmp));
			wsText = bsTmp;

			ConvertXMLStringToRTF(wsText, csRtf, unCodePage);
			csTmp = "{\\f0 ";
			csTmp += csRtf;
			csTmp += "\\par }";
			csOut += csTmp;
			pNode = pNodeList->nextNode();
		}

		csOut += "}";
   }
	catch (...)
   {
		csOut.LoadString(IDC_ERR_INVALIDDOC);
   }

	m_edRTF.SetWindowText(csOut);

	WriteFile(0);

	pNode = NULL;
	pNodeList = NULL;
	pDoc = NULL;
	CoUninitialize();
}



/*--------------------------------------------------------------------------*/

void CXmlConverterDlg::OnConvertToFlash() 
{
	CString                   csOut;
	CString                   csTmp;
	CString                   csFlash;
	_bstr_t                   bsText;
	BSTR                      bsTmp;
	wstring                   wsText;
	wstring                   wsTmp;
   _variant_t                varOut((bool)TRUE);
	IXMLDOMDocumentPtr        pDoc;
	IXMLDOMNodeListPtr        pNodeList;
	IXMLDOMNodePtr            pNode;
	IXMLDOMNodePtr            pNode2;
	IXMLDOMNamedNodeMapPtr    pNamedNodeMap;
	UINT                      unCodePage = GetCodePage();
	BOOL                      bStrict = (m_chkStrictSyntax.GetCheck() == 1);


	m_edXML.GetWindowText(csTmp);

   try
	{
      TESTHR(CoInitialize(NULL)); 
      TESTHR(pDoc.CreateInstance("msxml2.domdocument"));

      varOut = pDoc->loadXML(_bstr_t(csTmp));
      if ((bool)varOut == FALSE)
		{
			throw(0);
		}
		csOut = "";
		pNodeList = pDoc->getElementsByTagName("p");

		TESTHR(pNode = pNodeList->nextNode());
		while ( pNode != NULL )
		{
			TESTHR(pNode->get_attributes(&pNamedNodeMap));
			pNode2 = pNamedNodeMap->getNamedItem("id");
			if ( pNode2 == NULL )
			{
				pNode = pNodeList->nextNode();
				continue;
			}
			else
			{
				// Get ID value
				TESTHR(pNode2->get_text(&bsTmp));
				wsText = bsTmp;
				csTmp = "";
				for ( int i=0; i<wsText.length(); i++ )
				{
					csTmp += (char)wsText[i];
				}
				csTmp += '=';
			}

			TESTHR(pNode->get_text(&bsTmp));
			wsText = bsTmp;

			ConvertXMLStringToFlash(wsText, csFlash, unCodePage, bStrict);
			csTmp += csFlash;
			csTmp += "&"; // End of variable
			csOut += csTmp;
			pNode = pNodeList->nextNode();
		}

   }
	catch (...)
   {
		csOut.LoadString(IDC_ERR_INVALIDDOC);
   }

	m_edRTF.SetWindowText(csOut);

	WriteFile(1);

	pNode2 = NULL;
	pNode = NULL;
	pNamedNodeMap = NULL;
	pNodeList = NULL;
	pDoc = NULL;
	CoUninitialize();

}



/*--------------------------------------------------------------------------*/

void CXmlConverterDlg::OnView() 
{
	CString              csTmp;
	CString              csMsg;


	if ( m_csLastFile == "FromXML.txt" ) csTmp = "Flashi18n.html";
	else csTmp = m_csLastFile;

	if ( ((int)ShellExecute(AfxGetMainWnd()->GetSafeHwnd(), "open",
		csTmp, NULL, NULL, SW_SHOWNORMAL)) <= 32 )
	{
		csMsg.Format(IDC_ERR_CANTOPENFILE, csTmp);
		MessageBox(csMsg);
	}
}



/*--------------------------------------------------------------------------*/
// p_nType: 0=RTF, 1=Flash

void CXmlConverterDlg::WriteFile
(
	const int            p_nType
)
{
	FILE*                pFile;
	CString              csTmp;


	m_edRTF.GetWindowText(csTmp);
	if ( csTmp.IsEmpty() ) return; // Nothing to do

	switch ( p_nType )
	{
		case 0:
			m_csLastFile = "FromXML.rtf";
			break;

		case 1:
			m_csLastFile = "FromXML.txt";
			break;
	}

	pFile = fopen(m_csLastFile, "wt");
	if ( pFile == NULL )
	{

		AfxMessageBox(IDC_ERR_CANTCREATEFILE);
		return;
	}

	fputs(csTmp, pFile);
	fclose(pFile);
}



/*--------------------------------------------------------------------------*/

UINT CXmlConverterDlg::GetCodePage ()
{
	long                 lCodePage = CP_ACP;
	int                  n;
	CString              csTmp;
	char*                pszErr;


	if (( n = m_cbEncoding.GetCurSel()) != CB_ERR )
	{
		m_cbEncoding.GetLBText(n, csTmp);
		// Format = "NNN- text" this will gets us NNN
		lCodePage = strtol(csTmp, &pszErr, 10);
		if ( lCodePage < 1 ) lCodePage = CP_ACP;
	}

	return((UINT)lCodePage);
}



