//---------------------------------------------------------------------------


#pragma hdrstop

//---------------------------------------------------------------------------
#include <vcl.h>
#include <assert.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <Systobj.h>
#include <winsock.h>
#include <time.h>
#include <inifiles.hpp>
#include <math.h>

//---------------------------------------------------------------------------
#include "SysGlobalF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)

//---------------------------------------------------------------------------

String           g_sAppDir  = "";       // Application Directory
String           g_sAppName = "";       // Program name
String           g_sCfgDir  = "";       // Program Config Directory
String           g_sLogDir  = "";       // Program Log Directory
String           g_sTempDir = "";       // Program Temp Directory
String           g_sImgDir = "";        // Program Image Directory
String           g_sFormDir = "";       // Program Form Directory
String           g_sFtpDir  = "";       // Application Directory
//---------------------------------------------------------------------------

/*
 * 응용프로그램이 중복으로 실행되는 것을 막기위해 뮤텍스를 생성한다.
 *  arguments
 *
 *  return
 *      void
 */
bool SYS_ApplicationSingleInstance(AnsiString AProgName, AnsiString APidFile)
{
    bool       isRunning = false;
    HANDLE     hMutex = 0;
	AnsiString sMutexName;

	sMutexName = "Global\\" + AProgName;

	hMutex = CreateMutex(NULL, TRUE, sMutexName.c_str());
    if (hMutex && GetLastError() == ERROR_ALREADY_EXISTS)
    {
        char buffer[1000];

        ReleaseMutex(hMutex);
        hMutex=0;
        isRunning = true;

        ////////////////////////////////////////////////////////////////////////////

        AnsiString fn;
        char tmp[500];

        if (FileExists(APidFile))
        {
            TFileStream *fp = new TFileStream(APidFile, fmOpenRead);
            HWND hwnd;
            AnsiString nfo;

            memset(buffer, 0, 1000);
            fp->Read(buffer, 100);
            delete fp;

            hwnd = (HWND)(String(buffer).ToIntDef(0));
            if (hwnd)
            {
                SendMessage(hwnd, WM_USER, WM_WINDOW_RESTORE, 0);
            }
        }
    }

    if (hMutex)
    {
        ReleaseMutex(hMutex);
        hMutex=0;
    }

    return isRunning;
}
//---------------------------------------------------------------------------

/*
 * 응용프로그램의 중복실행을 막기위해 응용프로그램이 실행되면
 * 프로세스(윈도우핸들) 정보를 파일에 저장한다.
 *  arguments
 *
 *  return
 *      void
 */
void SYS_WritePidFile(long AHandle)
{
	char   tmp[500];
    String sPidFile;

    sPidFile = g_sCfgDir + ChangeFileExt(ExtractFileName(Application->ExeName), ".pid");

    try
    {
        TFileStream *fp = new TFileStream(sPidFile, fmCreate);
        memset(tmp, 0x00, sizeof(tmp));
        sprintf(tmp, "%d", (long)AHandle);
        fp->Write(tmp, strlen(tmp));
        delete fp;
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

/*
 * 환경설정 정보를 저장하는 함수.
 *  arguments
 *      String : RegisterKey 또는 파일이름
 *  return
 *      bool : 실패하면 false
 */
bool SYS_WriteConfigInfo(String sTitle, String sItem, String sValue, String sCfgFile/*=""*/)
{
	String	 ConfigFile;
	TIniFile *pIniFile = NULL;

    ConfigFile = sCfgFile;

    try
    {
        pIniFile = new TIniFile(ConfigFile);
        if (pIniFile == NULL)
        {
            return false;
        }

        pIniFile->WriteString(sTitle, sItem, sValue);
    }
    catch(...)
    {
    }

    if (pIniFile)
    {
        pIniFile->Free();
        pIniFile = NULL;
    }

	return true;
}
//---------------------------------------------------------------------------

/*
 * 환경설정 정보를 읽어오는 함수.
 *  arguments
 *      String : RegisterKey 또는 파일이름
 *  return
 *      bool : 실패하면 false
 */
bool ReadConfigInfo(String sTitle, String sItem, String &sValue, String sCfgFile/*=""*/)
{
    bool     bRes;
	String   ConfigFile;
	TIniFile *pIniFile = NULL;

    bRes = false;
    ConfigFile = sCfgFile;

    try
    {
        pIniFile = new TIniFile(ConfigFile);
        if (pIniFile == NULL)
        {
            return bRes;
        }

        sValue = pIniFile->ReadString(sTitle, sItem, "");
        if (sValue != "")
        {
            bRes = true;
        }
    }
    catch(...)
    {
    }

    if (pIniFile)
    {
        pIniFile->Free();
        pIniFile = NULL;
    }

	return bRes;
}
//---------------------------------------------------------------------------

String SYS_GetSysError()
{
    AnsiString sErrMsg  = "";
    LPVOID     lpMsgBuf = NULL;

    try
    {
        try
        {
            FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                GetLastError(),
                //MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
                (LPTSTR) &lpMsgBuf,
                0,
                NULL
            );

            char *pData = (char*)lpMsgBuf;
            if (strlen(pData) > 2)
            {
                pData[strlen(pData)-2] = 0x00;
                pData[strlen(pData)-1] = 0x00;
            }
            sErrMsg = AnsiString(pData);
        }
        __finally
        {
            if (lpMsgBuf) LocalFree(lpMsgBuf);
            lpMsgBuf = NULL;
        }
    }
    catch(Exception &e)
    {
    }
    return sErrMsg;
}
//---------------------------------------------------------------------------

