/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

!!IMPORTANT!!
This software(mcTool) uses parts of sources owned by Microchip Technology, Inc, 
and so these parts are not covered by this licence. 
See header of concerned files (mpfs2dynVar.cpp, mpfs2lib.cpp) for their own licence. 
////////////////////////////////////////////////////////////////////////////////
#Title: mcTool
#Project: mcTool
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<31/12/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
// xdcTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "mcTool.h"
#include <osdep/mswin/xbODregistry.h>
#include <xbVersion.h>
#include <xbRandom.h>
#include "mcTool_mpfs2.h"


int main(int argc, char* argv[])
{
	mcTool	mcTool(argc,(const char**)argv,false,true);

	bool bWriteHelp = false;
	try
	{
		mcTool.Start();

		eProtectBegin();
		{
			xbODregKey	key(xbODregClassesRoot,".mcTool");
			key.DefaultValue = "mcTool";
		}
		{
			xbODregKey	key(xbODregClassesRoot,"mcTool");
			key.Value["execPath"] = ::xbGetFilePath();
			key.DefaultValue = "xdCube Microchip tool";
			{
				xbODregKey	subkey(key,"DefaultIcon");
				subkey.DefaultValue = ::xbGetFilePath();// + ",-102";
			}

			xbODregKey	shellkey(key,"shell");
			{
				xbODregKey	subkey(shellkey,"open");
				subkey.DefaultValue = "Perform action with "+::xbGetProductName();
				
				xbODregKey	subkeycmd(subkey,"command");
				subkeycmd.DefaultValue = ::xbGetFilePath() + " \"%1\"";
			}
			{
				xbODregKey	subkey(shellkey,"edit");
				subkey.DefaultValue = "Edit with notepad";
				xbODregKey	subkeycmd(subkey,"command");
				subkeycmd.DefaultValue = "notepad.exe \"%1\"";
			}
		}
		eProtectEndDbgTrace();
		if (!mcTool.hasArg())
			bWriteHelp = true;

		g_xbRand.RandomInit(0);

		while(mcTool.hasArg())
		{
			mcTool.OpEnd();

			if (mcTool.hasSwitchArg())
			{
				xbString file(mcTool.getSwitchArg());
				mcTool.commandLoad(file);
				continue;
			}

			xbString arg(mcTool.getSwitch());
			if (arg.CompareNoCase("register") == 0) 
			{
				mcTool.bOpDone = true;
				continue;
			}
			if (arg.CompareNoCase("MPFS") == 0) 
			{
				mcTool.OpStart("MPFS generation");
				if (mcTool_MPFS2(mcTool))
					mcTool.bOpDone = true;
				continue;
			}

			if (arg.CompareNoCase("s") == 0) {mcTool.bSilent = true; continue;}
			if (arg.CompareNoCase("m") == 0) {mcTool.bMbox = false; continue;}
			if (arg.CompareNoCase("yes") == 0) {mcTool.questionAnswer = 1; continue;}
			if (arg.CompareNoCase("no") == 0) {mcTool.questionAnswer = -1; continue;}
			if (arg.CompareNoCase("help") == 0 || arg.CompareNoCase("h") == 0 || arg.CompareNoCase("?") == 0) 
			{
				bWriteHelp = true;
				continue;
			}

			xbThrow xbEuser(arg + " is an invalid switch");
		}


//		if (!bSilent) mcTool.fout << (LPCSTR)xbGetProductName() << " started... (mbox displayed="<< (LPCSTR)xbString(bMbox)<< ")\n";

		if (mcTool.bOpDone)
		{
			if (!mcTool.bSilent) 
			{
				mcTool.fout << (LPCSTR)xbGetProductName() << " finished...\n";
			}
		}
		else
		{
			if (!mcTool.bSilent) 
			{
				mcTool.fout << (LPCSTR)xbGetProductName() << " : nothing to do...\n";
				//bWriteHelp = true;
			}
		}
		if (bWriteHelp)
		{
			mcTool.fout << "Tools for Microchip developments\n";
			mcTool.fout << "     by mmm@devbooster.com : \n\n";

			mcTool.fout << (LPCSTR)xbGetProductName() << " HELP :\n\n";
			mcTool.fout << "SYNTAX :" << mcTool.GetAppName() << " [-...]\n";

			mcTool.fout << " > MPFS generation : \n";
			mcTool.fout << "     -mpfs [...] : mpfs2 generation\n";
			mcTool.fout << "     -mpfs ? : mpfs2 generation help\n";
			
			mcTool.fout << " > Global settings : \n";
			mcTool.fout << "     -s  : silent mode\n";
			mcTool.fout << "     -m  : don't display message boxes\n";
			mcTool.fout << "     -yes: answer yes to questions\n";
			mcTool.fout << "     -no : answer no to questions\n";
			mcTool.fout << "     -? or -h : this help screen\n";
//			mcTool.fout << "   Test accents: éè â € !\n";
		}
		if (mcTool.bOpDone)
		{
			if (mcTool.m_cWarning != 0)
			{
				mcTool.fout << "Work done successfully with "+xbString(mcTool.m_cWarning)+" warning(s).\n";
			}
			if (mcTool.bMbox) 
			{
				if (mcTool.m_cWarning != 0)
					::xbMBox(NULL,"Work done successfully with "+xbString(mcTool.m_cWarning)+" warning(s).\n(See console)","Warning",xbMBicon_Exclamation,xbMBbtn_Ok);
				else
					::xbMBox(NULL,"Work done successfully...","Information",xbMBicon_Information,xbMBbtn_Ok);
			}
		}
		else
		{
			if (mcTool.bMbox) 
				::xbMBox(NULL,"Nothing to do...","Information",xbMBicon_Information,xbMBbtn_Ok);
		}
	}
	catch(eMpfs2 *pE)
	{
		int ret = pE->GetHR();
		xbString msg(::xbGetMsg("console",pE));

		xbString ctx(xbGetCtx("console",pE));
		if (ctx.IsValid())
			mcTool.ferr << (LPCSTR)ctx << ":";

		mcTool.ferr << "error: " << msg << "\n";

		if (mcTool.bMbox) xbShowException(pE,true);
		else xbTraceException(pE,true);
		return ret;
	}
	catch(xbEbase *pE)
	{
		int ret = pE->GetHR();
		xbString msg(::xbGetMsg("console",pE));

		mcTool.ferr << (LPCSTR)xbGetProductName() << " : Error: " << msg << "\n";

		xbString ctx(xbGetCtx("console",pE));
		if (ctx.IsValid())
			mcTool.ferr << " -> error context : " << (LPCSTR)ctx << "\n";

		if (!mcTool.bSilent) 
		{
			mcTool.ferr << " -> type on command line : \n" << "'" << mcTool.GetAppName() << " -?' for help.\n";
			mcTool.ferr << " -> current directory : " << (LPCSTR)::xbGetCurrentDir() << "\n";
		}
		if (mcTool.bMbox) xbShowException(pE,true);
		else xbTraceException(pE,true);
		return ret;
	}
	catch(...)
	{
		mcTool.ferr << (LPCSTR)xbGetProductName() << " : Fatal Error: unknown exception !!\n";
		if (!mcTool.bSilent) 
		{
			mcTool.ferr << " -> type on command line : \n" << "'" << mcTool.GetAppName() << " -?' for help.\n";
			mcTool.ferr << " -> current directory : " << (LPCSTR)::xbGetCurrentDir() << "\n";
		}
		if (mcTool.bMbox) xbShowException(NULL);
		else xbTraceException(NULL);
		return E_POINTER;
	}

	return 0;
}

xbString mcTool::HTTPPrint_getHeaderAdd() const
{
	if (m_HTTPPrint_headerAdd.IsEmpty() || !m_HTTPPrint_headerAdd.StartWith("@"))
		return m_HTTPPrint_headerAdd;

	xbString file(m_HTTPPrint_headerAdd.Mid(1));
	xbFileStream stm(file,xbOpen,xbAccessR,xbWorkShared);
	xbString line;
	((mcTool*)this)->m_HTTPPrint_headerAdd.Empty();
	while(stm.ReadString(&line,(xbString*)NULL))
	{
		((mcTool*)this)->m_HTTPPrint_headerAdd += line+"\r\n";
	}
	return m_HTTPPrint_headerAdd;
}
