#include "CommonControl.h"


#include <windows.h>
#include <shlobj.h>
#include <mbstring.h>
#include <Shlwapi.h>
#include <objbase.h>
#include <commctrl.h>
#include <commdlg.h>
//#include <winnls32.h> こいつがあると、英語版Windowsで起動できねぇ！
#include <imm.h>
#include <basetsd.h>


#if _MSC_VER >= 1200
#pragma comment(lib,"comctl32")
#pragma comment(lib,"comdlg32")
#pragma comment(lib,"imm32")
#endif
;
namespace dkutil{

FolderSelector::FolderSelector(char *GetPath,size_t BuffSize,const char *folder,bool *flag){
	*flag = DKUTIL_SUCCEEDED(FolderSelectLogic(GetPath,BuffSize,folder,NULL,BIF_EDITBOX,NULL));
}

FolderSelector::FolderSelector(std::string &GetPath,const char *folder)
{
	GetPath.clear();
	char path[MAX_PATH]="";
	FolderSelect(path,sizeof(path),folder);
	GetPath = path;
}
	// コールバーク関数
int CALLBACK FolderSelector::BrowseCallbackProc( HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData )
{
	// フォルダ選択ダイアログの初期化
	if ( (BFFM_INITIALIZED == uMsg) && lpData ){
		SendMessage( hWnd, BFFM_SETSELECTION, TRUE, lpData );
	}
	return 0;
}//BrowseCallbackProc
int FolderSelector::select_with_file(std::string &buff,const char *folder,const char *title,HWND handle )
{
	char a[MAX_PATH * 2]="";
	UINT flag = BIF_BROWSEINCLUDEFILES | BIF_EDITBOX ;
	int r = FolderSelectLogic(a,sizeof(a),folder,title,flag,handle);
	buff = a;
	return r;
}
int FolderSelector::FolderSelect(char *GetPath,size_t BuffSize,const char *folder){
	return FolderSelectLogic(GetPath,BuffSize,NULL,NULL,BIF_EDITBOX,NULL);
}
int FolderSelector::FolderSelectLogic(char *GetPath,size_t BuffSize,
		const char *folder,const char *Title,
		UINT Flag,HWND WindowHandle)
	{
	if(BuffSize == 0) return edk_FAILED;
	char *pDir = GetPath;
	pDir[0] = '\0';

	HRESULT hr;
	BROWSEINFO bi={0};
	ITEMIDLIST *lpid = NULL;
	LPMALLOC pMalloc = NULL;

	bi.hwndOwner	= WindowHandle;
	bi.ulFlags		= Flag;
	if(!Title){
		bi.lpszTitle	= "ディレクトリ指定";
	}else{
		bi.lpszTitle = Title;
	}
	if(folder){
		bi.lpfn   = BrowseCallbackProc; // コールバーク関数
		bi.lParam = (LPARAM)folder;       // 初期フォルダ
	}
	//表示ing
	lpid = SHBrowseForFolder( &bi );

	if ( lpid == NULL )
	{
		//cancelが押された。
		return edk_Not_Selected;
	}
	else
	{
		hr = SHGetMalloc( &pMalloc );
		if ( hr == E_FAIL )
		{
			MessageBox(WindowHandle,  "SHGetMalloc Error", "Error",MB_OK);
			return edk_FAILED;
		}

		SHGetPathFromIDList( lpid, pDir );
		if ( pDir[strlen(pDir) - 1] != '\\' ){
			if(false==dkcFileExist(pDir))
			{//フォルダだったらフォルダにする。
				dkstrcat_amap(pDir,BuffSize,strlen(pDir),"\\",strlen("\\"));
			}
			//strcat( pDir, "\\" );
		}

		pMalloc->Free( lpid );
		pMalloc->Release();
	}
	return edk_SUCCEEDED;
}


}//end of dkutil namespace


