#include "Mix/Tool/Win32/Core/Directory.h"
#include <string.h>

namespace Mix{ namespace Tool{ namespace Win32{ namespace Directory{

	bool Modify( const wchar_t* pSrc, std::wstring& dst )
	{
		if( pSrc == NULL )
		{
			return false;
		}

		size_t len = ::wcslen( pSrc );
		if( len == 0 )
		{
			return false;
		}

		dst.clear();
		dst.reserve( len + 1 );

		for( size_t i = 0; i < len; i++ )
		{
			wchar_t code = pSrc[i];

			if( code == L'/' )
			{
				code = L'\\';
			}

			dst += code;
		}

		wchar_t lastCode = pSrc[len - 1];
		if( ( lastCode != L'\\' ) &&
			( lastCode != L'/' ) )
		{
			dst += L'\\';
		}

		return true;
	}

	bool Exists( const wchar_t* pPath )
	{
		if( ( pPath == NULL ) ||
			( ::wcslen( pPath ) == 0 ) )
		{
			return false;
		}

		HANDLE hFind;
		WIN32_FIND_DATA wfd;
		wchar_t lastCode;
		std::wstring searchPath;

		::ZeroMemory( &wfd, sizeof( wfd ) );

		searchPath = pPath;

		lastCode = pPath[::wcslen( pPath ) - 1];
		if( ( lastCode != L'\\' ) &&
			( lastCode != L'/' ) )
		{
			searchPath += L'\\';
		}

		searchPath += L"*.*";

		hFind = ::FindFirstFile( searchPath.c_str(), &wfd );
		if( hFind == INVALID_HANDLE_VALUE )
		{
			return false;
		}

		::FindClose( hFind );

		return true;
	}

	bool Create( const wchar_t* pPath, bool bFile )
	{
		if( ( pPath == NULL ) ||
			( ::wcslen( pPath ) == 0 ) )
		{
			return false;
		}

		std::wstring temp;

		temp.reserve( 2048 );

		for( unsigned int i = 0; pPath[i] != L'\0'; i++ )
		{
			wchar_t code = pPath[i];
			wchar_t nextCode = pPath[i + 1];

			if( ( code == L'\\' ) ||
				( code == L'/' ) ||
				( nextCode == L'\0' ) )
			{
				if( ( temp.size() == 2 ) &&
					( temp[1] == L':' ) )
				{
					//ドライブ
					;
				}
				else
				{
					if( ( nextCode == L'\0' ) &&
						( bFile == true ) )
					{
						//ファイル
						;
					}
					else
					{
						if( Exists( temp.c_str() ) == false )
						{
							if( nextCode == L'\0' )
							{
								temp += code;
							}

							if( ::CreateDirectory( temp.c_str(), NULL ) == FALSE )
							{
								return false;
							}
						}
					}
				}
			}

			temp += code;
		}

		return true;
	}

}}}}
