module yamalib.auxil.singleapp;

private import std.path;
private import std.string;
private import y4d_aux.filesys;
private import yamalib.log.log;

version(Win32){

struct _SECURITY_ATTRIBUTES {
    uint nLength;
    void* lpSecurityDescriptor;
    int bInheritHandle;
}
alias _SECURITY_ATTRIBUTES* LPSECURITY_ATTRIBUTES;
typedef void *HANDLE;

extern(Windows) export HANDLE CreateMutexA(
    LPSECURITY_ATTRIBUTES lpMutexAttributes,
    int bInitialOwner,
    char* lpName
    );

extern(Windows) export uint GetLastError();
extern(Windows) export int ReleaseMutex(HANDLE hMutex);
extern(Windows) export int CloseHandle(HANDLE hObject);
extern(Windows) export uint GetCurrentDirectoryA(uint CurrentDirSize, char* CurrrentDir);

}

/// アプリケーション二重起動抑止クラス
/// Windowsのみに対応
class SingleApp {
	static this() {
		char[256] curDir;
		char[] path;
		GetCurrentDirectoryA(curDir.length,&curDir[0]);
		path = .toString(&curDir[0]) ~ "+kyojintati4d.exe";
version(Win32){

		foreach (inout char c; path) {
			if (c == '\\') {
				c = '+';
			}
		}
		Log.print("unique id:%s",path);
		mutex =  CreateMutexA(null,true,cast(char*) path);
		if (GetLastError() == 183L) {
			valid = false;
		} else {
			valid = true;
		}
}
	}

	static ~this() {
version(Win32){
		if (mutex!=null) {
			ReleaseMutex(mutex);	//	所有権の解放
			CloseHandle(mutex);	//	生成したMutexの破壊
			mutex = null;
		}
}
	}

	static bool isValid() { return valid; }

private:
	static bool valid;
	static HANDLE mutex;
}