#include"../../Maid/FrameWork/Windows/CApplicationWindows.h"
#include"../../Maid/auxiliary/XML/CXMLReader.h"
#include"../../Maid/auxiliary/Windows/CShell.h"
#include"../../Maid/auxiliary/Windows/CRegistry.h"
#include"../../Maid/auxiliary/Cstring.h"


#include"SetupGlobal.h"
#include"resource.h"

#include<string>
#include<vector>

using namespace Maid;




class CApp : public IApplicationWindows
{
protected:
	virtual void OnSetup(){}
	virtual void OnCleanup(){}

	virtual void OnLoop()
	{
		const mstring UninstallInfo = GetCmdLine(1);

		if( ::MessageBox( NULL, "アンインストールしますか？", "確認", MB_YESNO )!=IDYES ) 
		{
			ApplicationExit();
			return; 
		}

		MySTL::vector<mstring> FileList;
		MySTL::vector<mstring> FolderList;

		mstring	guid;
		mstring	registry;

		{
			CXMLReader reader;

			reader.Load(UninstallInfo);

			reader.AscendNode();

			while( true )
			{
				if( reader.IsEndNode() ) { break; }
				const mstring NodeName = reader.GetNodeName();

				if( NodeName==MAIDTEXT(s_UNINSTALLER_COPYFILE) )
				{
					FileList.push_back( CString::ToLower(reader.GetString()) );
				}
				ef( NodeName==MAIDTEXT(s_UNINSTALLER_SHORTCUT) )
				{
					FileList.push_back( CString::ToLower(reader.GetString()) );
				}
				ef( NodeName==MAIDTEXT(s_UNINSTALLER_CREATEFOLDER) )
				{
					FolderList.push_back( CString::ToLower(reader.GetString()) );
				}
				ef( NodeName==MAIDTEXT(s_UNINSTALLER_GUID) )
				{
					guid = CString::ToLower(reader.GetString());
				}
				ef( NodeName==MAIDTEXT(s_UNINSTALLER_CREATEREGISTRY) )
				{
					registry = CString::ToLower(reader.GetString());
				}
				reader.NextNode();
			}

			FileList.push_back(UninstallInfo);
		}

		//	読み込んだリストを順番に削除していく

		for( int i=0; i<(int)FileList.size(); ++i )
		{
			try
			{
				const mstring& str = FileList[i];
				CShell::DeleteFile( str );
			}catch(...){}
		}
		for( int i=0; i<(int)FolderList.size(); ++i )
		{
			try
			{
				const mstring& str = FolderList[i];
				CShell::DeleteDirectory( str );
			}catch(...){}
		}



		//	レジストリの削除
		{
			CRegistry::DeleteKey( CRegistry::KEY_CURRENT_USER, registry );

			CRegistry::DeleteKey( CRegistry::KEY_LOCAL_MACHINE, MAIDTEXT(s_UNINSTALLER_CTRLPANEL) + MAIDTEXT("\\") + guid );
		}

		::MessageBox( NULL, "アンインストールが終わりました", "確認", MB_OK );	
	
		ApplicationExit();
	}
};



int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	CApp capp;
	return capp.Run( hInstance, hPrevInstance, lpCmdLine, nCmdShow );
}
