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

#include <vcl.h>
#include <windows.h>
#include <inifiles.hpp>
#include <stdio.h>
#include <shellapi.h>
#include "MultiLanguage.h"
#include "Environment.h"
#include "Message_Form.h"

#pragma hdrstop
//---------------------------------------------------------------------------
USEFORM("..\Common_PC\AdvMachineControl_Form.cpp", AdvMachineControlForm);
USEFORM("..\Common_PC\Alarm_Form.cpp", AlarmForm);
USEFORM("..\Common_PC\AuditTrail_Form.cpp", AuditTrailForm);
USEFORM("..\Common_PC\CalendarDialog_Form.cpp", CalendarDialogForm);
USEFORM("..\Common_PC\Calibration3D_Form.cpp", Calibration3DForm);
USEFORM("..\Common_PC\CalibrationMenu_Form.cpp", CalibrationMenuForm);
USEFORM("..\Common_PC\CameraSetting3D_Form.cpp", CameraSetting3DForm);
USEFORM("..\Common_PC\ColorCode_Form.cpp", ColorCodeForm);
USEFORM("..\Common_PC\CommControl_Form.cpp", CommControlForm);
USEFORM("..\Common_PC\CPBSetting_Form.cpp", CPBSettingForm);
USEFORM("..\Common_PC\CPBStatus_Form.cpp", CPBStatusForm);
USEFORM("..\Common_PC\DataMatching_Form.cpp", DataMatchingForm);
USEFORM("..\Common_PC\DiskSpaceManagerSetting_Form.cpp", DiskSpaceManagerSettingForm);
USEFORM("..\Common_PC\Download_Form.cpp", DownloadForm);
USEFORM("..\Common_PC\ErrorList_Form.cpp", ErrorListForm);
USEFORM("..\Common_PC\HPITest_Form.cpp", HPITestForm);
USEFORM("..\Common_PC\InputText_Dialog.cpp", InputTextDialog);
USEFORM("..\Common_PC\IntervalSetting_Form.cpp", IntervalSettingForm);
USEFORM("..\Common_PC\IOSetting_Form.cpp", IOSettingForm);
USEFORM("..\Common_PC\Keyboard_Form.cpp", KeyboardForm);
USEFORM("..\Common_PC\LogIn_Form.cpp", LogInForm);
USEFORM("..\Common_PC\LogViewer_Form.cpp", LogViewerForm);
USEFORM("..\Common_PC\MachineControl_Form.cpp", MachineControlForm);
USEFORM("..\Common_PC\MachineParamSetting_Form.cpp", MachineParamSettingForm);
USEFORM("..\Common_PC\MachineSetting_Form.cpp", MachineSettingForm);
USEFORM("..\Common_PC\MachineSetup_Form.cpp", MachineSetupForm);
USEFORM("Main_Form.cpp", MainForm);
USEFORM("..\Common_PC\MCBSPTest_Form.cpp", MCBSPTestForm);
USEFORM("..\Common_PC\Message_Form.cpp", MessageForm);
USEFORM("..\Common_PC\MotorSetting_Form.cpp", MotorSettingForm);
USEFORM("..\Common_PC\MotorSpeedSelection_Form.cpp", MotorSpeedSelectionForm);
USEFORM("..\Common_PC\NCControl_Form.cpp", NCControlForm);
USEFORM("..\Common_PC\NCSetting_Form.cpp", NCSettingForm);
USEFORM("..\Common_PC\NewTabletCounter_Form.cpp", NewTabletCounterForm);
USEFORM("..\Common_PC\PrintInspectionResult_Form.cpp", PrintInspectionResultForm);
USEFORM("..\Common_PC\ProductInput_Form.cpp", ProductInputForm);
USEFORM("..\Common_PC\ProductSearch_Form.cpp", ProductSearchForm);
USEFORM("..\Common_PC\Progress_Form.cpp", ProgressForm);
USEFORM("..\Common_PC\QuickStart_Form.cpp", QuickStartForm);
USEFORM("..\Common_PC\RequestPasswordChange_Form.cpp", RequestPasswordChangeForm);
USEFORM("..\Common_PC\RS485Test_Form.cpp", RS485TestForm);
USEFORM("..\Common_PC\SetPath_Form.cpp", SetPathForm);
USEFORM("..\Common_PC\Setup_Form.cpp", SetupForm);
USEFORM("..\Common_PC\SpeedControl_Form.cpp", SpeedControlForm);
USEFORM("..\Common_PC\SystemMonitor_Form.cpp", SystemMonitorForm);
USEFORM("..\Common_PC\SystemProcessInfo_Form.cpp", SystemProcessInfoForm);
USEFORM("..\Common_PC\SystemSetting_Form.cpp", SystemSettingForm);
USEFORM("..\Common_PC\TabletCounter_Form.cpp", TabletCounterForm);
USEFORM("..\Common_PC\TabletDataLog_Form.cpp", TabletDataLogForm);
USEFORM("..\Common_PC\TerminateWaiting_Form.cpp", TerminateWaitingForm);
USEFORM("..\Common_PC\UnmanedOperation_Form.cpp", UnmanedOperationForm);
USEFORM("..\Common_PC\USBMessage_Form.cpp", USBMessageForm);
USEFORM("..\Common_PC\UserRegister_Form.cpp", UserRegisterForm);
USEFORM("..\Common_PC\Virtual_CPB_Form.cpp", VirtualCPBForm);
USEFORM("..\Common_PC\Virtual_SPB_Form.cpp", VirtualSPBForm);
USEFORM("..\Common_PC\VirtualImageControl_Form.cpp", VirtualImageControlForm);
USEFORM("..\Common_PC\VirtualMachine_Form.cpp", VirtualMachineForm);
USEFORM("..\Common_PC\Waiting_Form.cpp", WaitingForm);
USEFORM("..\Common_PC\Warning_Form.cpp", WarningForm);
USEFORM("..\Common_PC\SelectDefectImage_Form.cpp", SelectDefectImageForm);
USEFORM("..\Common_PC\PrintAuditTrail_Form.cpp", PrintAuditTrailForm);
USEFORM("..\Common_PC\StudySpeedControl_Form.cpp", StudySpeedControlForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\SystemSimulation_Form.cpp", SystemSimulationForm);
USEFORM("..\Common_PC\InspectionStatus_Form.cpp", InspectionStatusForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\PrintAuditTrail_Ajanta_Form.cpp", PrintAuditTrail_Ajanta_Form);
USEFORM("..\Common_PC\PrintInspectionResult_Ajanta_Form.cpp", PrintInspectionResult_Ajanta_Form); /* TTntForm: File Type */
USEFORM("..\Common_PC\ThreeDLineScanFrequencyStudy_Form.cpp", ThreeDLineScanFrequencyStudyForm);
USEFORM("..\Common_PC\InspectionReport_Form.cpp", InspectionReportForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\InspectionRecover_Form.cpp", InspectionRecoverForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\InspectionResultInsert_Form.cpp", InspectionResultInsertForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\RealSizeImage_Form.cpp", RealSizeImageForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\SystemInfo_Form.cpp", SystemInfoForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\UserAuthoritySetting_Form.cpp", UserAuthoritySettingForm);
USEFORM("..\Common_PC\Capture_Frame.cpp", CaptureFrame); /* TFrame: File Type */
USEFORM("..\Common_PC\client.cpp", ClientForm);
USEFORM("..\Common_PC\ComputerSystemSetting_Form.cpp", ComputerSystemSettingForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\EnvironmentSetting_Form.cpp", EnvironmentSettingForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\GradeSetting.cpp", GradeSettingForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Graph_Check_Form.cpp", Graph_CheckForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\HR_SpecialForm.cpp", HR_SpecialInsForm);
USEFORM("..\Common_PC\MachineSetupMenu_Form.cpp", MachineSetupMenuForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\MachineSetupProcess_Form.cpp", MachineSetupProcessForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\MachineTest_Form.cpp", MachineTestForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\AutoBrightnessSetting_Form.cpp", AutoBrightnessSettingForm);
USEFORM("..\Common_PC\Camera_Interface\Calibration_Form.cpp", CalibrationForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\CameraMapping_Form.cpp", CameraMappingForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\Capture_Form.cpp", CaptureForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\DefectInfo_Form.cpp", DefectInfoForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\First_Study.cpp", FirstStudy); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\Inspection_Form.cpp", InspectionForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\InspectionAreaRevision_Form.cpp", InspectionAreaRevisionForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\InspectionSetup_Form.cpp", InspectionSetupForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\MachineEnvSetup_Form.cpp", MachineEnvSetupForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\MachineSettingTest_Form.cpp", MachineSettingTestForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\NFA2DCameraSetting_Form.cpp", NFA2DCameraSettingForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\PreviewInspection_Form.cpp", PreviewInspectionForm);
USEFORM("..\Common_PC\Camera_Interface\Study_Form.cpp", StudyForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\TabletCharacterExtract.cpp", TabletCharacterExtractForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\Camera_Interface\TwoDCalibrationGuide_Form.cpp", TwoDCalibrationGuideForm);
USEFORM("..\Common_PC\Camera_Interface\VisionSetting_Form.cpp", VisionSettingForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\SpecialIns_Form.cpp", SpecialInsForm);
USEFORM("..\Common_PC\NavigateDefectImage_Form.cpp", NavigateDefectImageForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\ThreeDPrintMask_Form.cpp", ThreeDPrintMaskForm);
USEFORM("..\Common_PC\ThreeDSensorStatusCheck_Form.cpp", ThreeDSensorStatusCheckForm);
USEFORM("..\Common_PC\Camera_Interface\OffSetImageExtract_Form.cpp", OffSetImageExtractForm);
USEFORM("..\Common_PC\LaserInspectionMarkingInfo_Form.cpp", LaserInspectionMarkingInfoForm); /* TTntForm: File Type */
USEFORM("..\Common_PC\HCBMonitoring_Form.cpp", HCBMonitoringForm);
USEFORM("..\Common_PC\Camera_Interface\LaserCalibration_Form.cpp", LaserCalibrationForm);
USEFORM("..\Common_PC\Camera_Interface\CameraTest_Form.cpp", CameraTestForm);
USEFORM("..\Common_PC\Camera_Interface\TPBCameraSetting_Form.cpp", TPBCameraSettingForm);
//---------------------------------------------------------------------------
int LoadFileFlag = 0;
WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	try
	{
    /***************************************************************************************************************************************/
    // 2018-09-13
    // Starter 프로그램에서 보드 연결상태를 확인하기위해 주기적으로 보드연결/해제를 반복하는데 이때 소켓이 Starter프로그램에서 열려있는 경우
    // 본 프로그램에서 통신 장애가 발생하므로 이에 대한 간섭을 피하기 위해 일정 딜레이를 적용하여 프로그램을 실행한다.
    Sleep(500);
    /***************************************************************************************************************************************/

		const char mutexname[] = "vm_main_application";

    AnsiString RootPath;
    RootPath = ExtractFileDir(Application->ExeName);

    AnsiString PIDFileNameA, PIDFileNameB, DebugFileName;
    PIDFileNameA = RootPath + "\\tvmsm15p.dat";
    PIDFileNameB = RootPath + "\\tvmsm20.dat";
    DebugFileName = RootPath + "\\swdebug.ini";

    GlobalProgramID = PROGRAM_ID_NONE;
    
    bool bPIDError = false;
    bool bExistPIDFileA, bExistPIDFileB, bExistDebugFile;

    bExistPIDFileA = FileExists(PIDFileNameA);
    bExistPIDFileB = FileExists(PIDFileNameB);
    bExistDebugFile = FileExists(DebugFileName);

    if(bExistDebugFile)
    {
      TIniFile *iniFile = new TIniFile(DebugFileName);
      if (iniFile)
      {
        GlobalProgramID = iniFile->ReadInteger("Debugging", "Program ID", PROGRAM_ID_200); // 0 : 200, 1 : 150p, 2 : 200
        delete iniFile;
      }

      if(GlobalProgramID != PROGRAM_ID_150P && GlobalProgramID != PROGRAM_ID_200)
      {
        ShowMessageW("Invalid value [System ID]");
        return 0;
      }
    }
    else
    {
      if(!bExistPIDFileA && !bExistPIDFileB) // id file이 모두 존재하지 않는 경우
      {
        bPIDError = true;
      }
      else if(bExistPIDFileA && bExistPIDFileB) // id file 이 모두 존재하는 경우
      {
        bPIDError = true;
      }

      if(!bPIDError)
      {
        TFileStream *fileStream;
        char pidBuff[PROGRAM_ID_FILE_SIZE];

        if(bExistPIDFileA)
        {
          fileStream = new TFileStream(PIDFileNameA, fmOpenRead);
          fileStream->Read(pidBuff, PROGRAM_ID_FILE_SIZE);

          if(pidBuff[PROGRAM_ID_ADDRESS_A] == 'F' &&
              pidBuff[PROGRAM_ID_ADDRESS_B] == '1' &&
              pidBuff[PROGRAM_ID_ADDRESS_C] == '5' &&
              pidBuff[PROGRAM_ID_ADDRESS_D] == '+' &&
              pidBuff[PROGRAM_ID_ADDRESS_E] == 'A')
          {
            GlobalProgramID = PROGRAM_ID_150P;
          }
        }
        else if(bExistPIDFileB)
        {
          fileStream = new TFileStream(PIDFileNameB, fmOpenRead);
          fileStream->Read(pidBuff, PROGRAM_ID_FILE_SIZE);

          if(pidBuff[PROGRAM_ID_ADDRESS_A] == '2' &&
              pidBuff[PROGRAM_ID_ADDRESS_B] == 'A' &&
              pidBuff[PROGRAM_ID_ADDRESS_C] == '0' &&
              pidBuff[PROGRAM_ID_ADDRESS_D] == '0' &&
              pidBuff[PROGRAM_ID_ADDRESS_E] == 'F')
          {
            GlobalProgramID = PROGRAM_ID_200;
          }
        }
        delete fileStream;

        if(GlobalProgramID != PROGRAM_ID_150P && GlobalProgramID != PROGRAM_ID_200)
        {
          ShowMessageW("Invalid value [System ID]");
          return 0;
        }
      }
      else
      {
        ShowMessageW("Invalid value [System ID]");
        return 0;
      }
    }

		HANDLE hMutex = NULL;

		hMutex = OpenMutexA(SYNCHRONIZE, false, mutexname);
		if (hMutex==NULL)
		{
      //프로그램을 실행하기전 Language 데이터를 먼저 가져옴
      if(!LoadFromFile(RootPath + "\\Env\\TLanguage.dat"))
      {
        CloseHandle(hMutex);
        ShowMessageW("Cannot read Language.dat");
      }
      else
      {
        LoadFileFlag = 1;
        SetDefaultLocaleInfo();
        GetStringData();
        Free_StringStruct();
        LoadFileFlag = 0;
      }
			hMutex = CreateMutexA(NULL, true, mutexname);
		}
		else
    {
			CloseHandle(hMutex);
			ShowMessageW("The program is already running.");
			return 0;
		}

    /*
    ActiveMode Select
    * 프로그램 실행 시 넘어온 인자 분석하여 ActiveMode에 사용한다.
    * SELMA 100 기준      = SELMA.exe -LCID 1234   - [프로그램 이름 , LCID]
    * SELMA 150,200 기준  = SELMA.exe 2 -LCID 1234 - [프로그램 이름 , ActiveMode Number , LCID]
    * szArglist 배열 [1]번째에 담기는 값을 파악하여 사용
    */

    LPWSTR *szArglist;
    int nArgs;
    int i;

    szArglist = CommandLineToArgvW(GetCommandLineW(),&nArgs);
    if(NULL != szArglist)
    {
      if(nArgs >= 2)
      {
        String LengthCheck =(szArglist[1]);
        if(LengthCheck.Length() == 1)
        {
          if(StrToInt(szArglist[1])>= 1 || StrToInt(szArglist[1])<= 3)
          {
            TIniFile *iniFile = new TIniFile(RootPath + "\\Env" +"\\UserSetting.ini");
            if (iniFile)
            {
              iniFile->WriteInteger("RecentBoardActiveStatus","Active",StrToInt(szArglist[1]));
              delete iniFile; // 1-usb all 2-hcb-usb/tcp-spb  3-tcp all
            }
          }
        }
      }
    }

		Application->Initialize();
    if(DefaultLCID == 1041)
      Application->Title = "ACROCIA";
    else
  		Application->Title = "TVM_Application";

     Application->CreateForm(__classid(TMainForm), &MainForm);
		Application->CreateForm(__classid(TErrorListForm), &ErrorListForm);
		Application->CreateForm(__classid(TTabletCounterForm), &TabletCounterForm);
		Application->CreateForm(__classid(TWarningForm), &WarningForm);
		Application->CreateForm(__classid(TWaitingForm), &WaitingForm);
		Application->CreateForm(__classid(TKeyboardForm), &KeyboardForm);
		Application->CreateForm(__classid(TNCControlForm), &NCControlForm);
		Application->CreateForm(__classid(TSystemMonitorForm), &SystemMonitorForm);
		Application->CreateForm(__classid(TAdvMachineControlForm), &AdvMachineControlForm);
		Application->CreateForm(__classid(TSystemProcessInfoForm), &SystemProcessInfoForm);
		Application->CreateForm(__classid(TGraph_CheckForm), &Graph_CheckForm);
		Application->CreateForm(__classid(TClientForm), &ClientForm);
		Application->CreateForm(__classid(TInspectionAreaRevisionForm), &InspectionAreaRevisionForm);
		Application->CreateForm(__classid(TInspectionStatusForm), &InspectionStatusForm);
		Application->CreateForm(__classid(TUserAuthoritySettingForm), &UserAuthoritySettingForm);
		Application->CreateForm(__classid(TThreeDSensorStatusCheckForm), &ThreeDSensorStatusCheckForm);
		Application->CreateForm(__classid(TTPBCameraSettingForm), &TPBCameraSettingForm);
		Application->Run();
	}
	catch (Exception &exception)
	{
		Application->ShowException(&exception);
	}
	catch (...)
	{
		try
		{
			throw Exception("");
		}
		catch (Exception &exception)
		{
			Application->ShowException(&exception);
		}
	}
  if(LoadFileFlag)
    Free_StringStruct();
	return 0;
}
//---------------------------------------------------------------------------














