//---------------------------------------------------------------------------
#ifndef EnvironmentH
#define EnvironmentH
//---------------------------------------------------------------------------
#include "common.h"
//#include "command_spb_sys.h"
//#include "command_spb_app.h"
#include "Command.h"
#include "Common_PC.h"
//#include "USBConnection.h"
#include "Processing.h"
#include "DiskSpacemanager.h"
#include "CommControl_Form.h"
#include "InspectionSetup_Form.h"
#include "Message_Form.h"
#include "Keyboard_Form.h"

#include "CSVLog.h"
#include "FileContainer.h"
#include "MachineControl.h"
#include "TntStdCtrls.hpp"
#include "TntExtCtrls.hpp"
#include "TntGrids.hpp"
#include <Grids.hpp>
#include <QRCtrls.hpp>
#include <QuickRpt.hpp>

#include<iostream>
#include <string>
#include<map.h>
using namespace std;
#include<vector>

//---------------------------------------------------------------------------
#define TARGET_PROJECT_NAME				"TVM_Applications"
#define TARGET_HCB_PROGRAM_REV			106		// data structure가 같음을 의미한다.
#define TARGET_HCB_DATA_REV				106
#define TARGET_SPB_PROGRAM_REV			105
#define TARGET_SPB_DATA_REV				105

#define USER_STATUS_LOGOUT				    0
#define USER_STATUS_LOGIN				      1
#define USER_STATUS_INQUIRE_LOGOUT    2

#define MAX_FRAME_BUFFER_COUNT      	128

#define DEFECT_DATA_CONTAINER_SIZE			1000

#define THROUGHPUT_FILE_VERSION			100
#define THROUGHPUT_CHART_DEFAULT_SIZE	360		// 1 hour

#define TPB_BOARD_NONE	0
#define TPB_BOARD_EXSIT	1

//---------------------------------------------------------------------------
typedef enum {EPDBR_MACHINE_SETUP, EPDBR_MACHINE_SETTING_CHANGE, EPDBR_PRODUCT_INFO_CHANGE, EPDBR_DATA_RESTORE} EProductDataBackupReason;
typedef enum {EIK_NORMAL, EIK_OPTION} EImageKind;

#define MIN_AUTHORITY_COUNT 4 // (SYSTEM + 사용자 지정 최소 권한 3개)
#define MAX_AUTHORITY_COUNT 8 // (SYSTEM + 사용자 지정 최대 권한 7개)
#define MAX_UI_ACCESS_EVENT 49 // (42(e) + 5(n))
#define SYSTEM_ACCESS_LEVEL_ANONYMOUS    -1
#define SYSTEM_HIGHEST_ACCESS_LEVEL       0

#define MAX_MOTOR_SPEED 1000000

#define THREED_SENSOR_OFF   0
#define THREED_SENSOR_ON    1

#define THREED_SENSOR_NONE_MODE   0
#define THREED_SENSOR_CALIB_MODE  1

#define THREED_SENSOR_ERROR_CODE_GOOD                 0
#define THREED_SENSOR_ERROR_CODE_BRD_DISCONNECTED     1
#define THREED_SENSOR_ERROR_CODE_INVALID_MAPPING      2
#define THREED_SENSOR_ERROR_CODE_CAMERA_DISCONNECTED  3

#define PROGRAM_ID_NONE 0
#define PROGRAM_ID_150P 1
#define PROGRAM_ID_200  2

#define PROGRAM_ID_FILE_SIZE  128
#define PROGRAM_ID_ADDRESS_A  3
#define PROGRAM_ID_ADDRESS_B  4
#define PROGRAM_ID_ADDRESS_C  15
#define PROGRAM_ID_ADDRESS_D  17
#define PROGRAM_ID_ADDRESS_E  54

extern int ThreeDSensorActiveStatus;
extern int Disk1ThreeDSensorErrorCode;
extern int Disk2ThreeDSensorErrorCode;

extern int RecentDisk1ThreeDCameraLSFValue;
extern int RecentDisk2ThreeDCameraLSFValue;

extern unsigned char DefectBayerImage[SYSTEM_CAMERA_WIDTH * SYSTEM_CAMERA_HEIGHT];

extern int GlobalProgramID;
extern bool SystemLinkCameraInfo[SYSTEM_TOTAL_CAMERA_COUNT];
extern AnsiString SystemCameraID[SYSTEM_TOTAL_CAMERA_COUNT];

typedef enum
{
  ACCESS_PGM_EVT_MAINFORM_LOG_IN,
  ACCESS_PGM_EVT_MAINFORM_PRODUCT_INFO,
  ACCESS_PGM_EVT_PRODUCTINPUTFORM_MAKE_NEW_PRODUCT,
  ACCESS_PGM_EVT_PRODUCTINPUTFORM_SEARCH_PRODUCT,
  ACCESS_PGM_EVT_PRODUCTINPUTFORM_CHANGE_NAME,
  ACCESS_PGM_EVT_PRODUCTINPUTFORM_MAKE_CLONE,
  ACCESS_PGM_EVT_PRODUCTINPUTFORM_CHANGE_DATA_INFO,
  ACCESS_PGM_EVT_PRODUCTINPUTFORM_DELETE_DATA_INFO,
  ACCESS_PGM_EVT_MAINFORM_MACHINE_SETUP,
  ACCESS_PGM_EVT_MACHINESETUPFORM_NEW_SETUP,
  ACCESS_PGM_EVT_MACHINESETUPFORM_EXIST_SETUP,
  ACCESS_PGM_EVT_MACHINESETUPFORM_ADJUST_VALUE,
  ACCESS_PGM_EVT_MACHINESETUPFORM_TEST,
  ACCESS_PGM_EVT_MAINFORM_CAPTURE,
  ACCESS_PGM_EVT_CALIBRATIONFORM_CAPTURE_START,
  ACCESS_PGM_EVT_CALIBRATIONFORM_CAPTURE_STOP,
  ACCESS_PGM_EVT_CALIBRATIONFORM_BRIGHTNESS_SETUP,
  ACCESS_PGM_EVT_CALIBRATIONFORM_SPEED_CONTROL,
  ACCESS_PGM_EVT_CALIBRATIONFORM_AREA_SETUP,
  ACCESS_PGM_EVT_CALIBRATIONFORM_RESOLUTION_SETUP,
  ACCESS_PGM_EVT_CALIBRATIONFORM_3D_CAMERA_SETUP,
  ACCESS_PGM_EVT_CALIBRATIONFORM_CAMERA_SETUP,
  ACCESS_PGM_EVT_MAINFORM_FEATURE_EXTRACTION,
  ACCESS_PGM_EVT_MAINFORM_FIRST_STUDY,
  ACCESS_PGM_EVT_MAINFORM_SECOND_STUDY,
  ACCESS_PGM_EVT_SEC_STUDY_FORM_ADJUST_VALUE,
  ACCESS_PGM_EVT_MAINFORM_INSPECTION,
  ACCESS_PGM_EVT_INSPECTIONFORM_GRADESETTING,
  ACCESS_PGM_EVT_INSPECTIONFORM_CAMERA_SETUP,
  ACCESS_PGM_EVT_MAINFORM_INSPECTION_HISTORY,
  ACCESS_PGM_EVT_MAINFORM_LOG_OUT,
  ACCESS_PGM_EVT_MAINFORM_CLEANING_STANDBY,
  ACCESS_PGM_EVT_MAINFORM_DEVICE_CONTROL,
  ACCESS_PGM_EVT_MAINFORM_USER_ADMINISTRATION,
  ACCESS_PGM_EVT_USERRESISTERFORM_REGIST,
  ACCESS_PGM_EVT_USERRESISTERFORM_DELETE,
  ACCESS_PGM_EVT_USERRESISTERFORM_CHANGE_PW,
  ACCESS_PGM_EVT_MAINFORM_ENV_SETUP,
  ACCESS_PGM_EVT_ENVSETUPFORM_COM_SYS_SETUP,
  ACCESS_PGM_EVT_ENVSETUPFORM_PGM_SETUP,
  ACCESS_PGM_EVT_ENVSETUPFORM_SECURITY_SETUP,
  ACCESS_PGM_EVT_ENVSETUPFORM_AUTHORITY_SETUP,
  ACCESS_PGM_EVT_ENVSETUPFORM_COMM_SETUP,
  ACCESS_PGM_EVT_ENVSETUPFORM_STORAGE_SPACE_SETUP,
  ACCESS_PGM_EVT_ENVSETUPFORM_RUN_DMU,
  ACCESS_PGM_EVT_ENVSETUPFORM_AIR_CONTROL,
  ACCESS_PGM_EVT_MAINFORM_SYSTEM_SETUP,
  ACCESS_PGM_EVT_MAINFORM_AUDIT_TRAIL,
  ACCESS_PGM_EVT_MAINFORM_EXIT,

}EAccessProgramEvent;

typedef struct
{
  int SystemAuthorityCount;
  WideString ProgramAccessAuthorityName[MAX_AUTHORITY_COUNT];
  WideString ProgramAccessEventSerialNumber[MAX_UI_ACCESS_EVENT];
  WideString ProgramAccessEventDescription[MAX_UI_ACCESS_EVENT];
  bool ProgramAccessAuthorityTable[MAX_AUTHORITY_COUNT][MAX_UI_ACCESS_EVENT];
} TProgramAccessAuthorityData;

extern TProgramAccessAuthorityData ProgramAccessAuthorityData;
extern bool bInitProgramAuthority;

extern bool SimulationMode;

extern int InspectionKind;
extern int InspectionOrStudy;

typedef struct
{
	unsigned int SendDataLength;
  unsigned int ReceivedDataLength;
} TCommDataLength;

typedef struct
{
	int Status;
	int AccessLevel;
  AnsiString Name;
} TUserInfo;

extern TTabletGradeData TabletGradeData_PC;
extern TTabletStudyResultData TabletStudyResultData_PC;

#define PC_TABLET_LIST_COUNT			512
typedef struct
{
	int TabletNumber;
	int InspectionResult;
	int InspectionResult_SPB[SYSTEM_SPB_MAX_COUNT];
	int HCBState;
	unsigned int Sensor1Time;
	unsigned int EstimatedSensor2Time;
	unsigned int Sensor2Time;
	unsigned int Sensor3Time;
    int Sensor1Length;
    int Sensor1Interval;
    double Sensor1TabletGap;
    int Sensor2Length;
    int Sensor2Interval;
    double Sensor2TabletGap;

	int IsLEDOn[SYSTEM_MACHINE_CAPTURE_COUNT];
    int SPBState[SYSTEM_SPB_MAX_COUNT];
} TPCTabletUnit;

extern TMachineParams MachineParams;

extern TUserInfo UserInfo;
extern TProgramPath ProgramPath;
extern TProductData ProductData;
extern TMachineSetupData MachineSetupData;
extern TCameraMapInfo CameraMapInfo[SYSTEM_TOTAL_CAMERA_COUNT];
extern TSPBSystemSetupData SPBSystemSetupData[SYSTEM_SPB_MAX_COUNT];
extern TVariableCameraInformation VariableCameraInformation[SYSTEM_TOTAL_CAMERA_COUNT];
extern TThreeDCameraDefaultInformation ThreeDCameraDefaultInformation[SYSTEM_TOTAL_CAMERA_COUNT];
extern TWhiteBalanceInfo WhiteBalanceInfo[SYSTEM_TOTAL_CAMERA_COUNT];
extern TMachineOperationInfo MachineOperationInfo;

extern TDSMThread *DSMThread;
extern TDSMInfo DSMInfo;
extern TProgramVersion ProgramVersion;

extern TPcUiFlag PcUiFlag;

typedef struct
{
	bool InactivityLogoutEnabled;
	int InactivityTimeout;
	bool PasswordExpirationEnabled;
	int PasswordExpirationTime;
	int PasswordMinLength;
  bool FirstLoginChangePW;
  int PasswordFailAvailableCount;
} TComputerSystemInfo;
extern TComputerSystemInfo ComputerSystemInfo;

typedef struct
{
	bool StudySetupDataValid;
	bool InspectionSetupDataValid;
	bool GradeDataValid;
} TCPBSetupInfo;
extern TCPBSetupInfo CPBSetupInfo;

typedef struct
{
	int CurrentTemperature[3];
	int CurrentHumidity[3];
	int InverterSpeed[3];
	double Pressure[3];
} TSystemMonitorInfo;
extern TSystemMonitorInfo SystemMonitorInfo;

typedef struct
{
	AnsiString TargetProjectName;
	AnsiString TargetMachineName;
	unsigned int TargetHCBDataRev;
	unsigned int TargetSPBDataRev;
} TPCSystemHeader;
extern TPCSystemHeader PCSystemHeader;

extern TInitialValues InitialValues;

typedef struct
{
	bool SPB_HCB_InsCntMatchingOptionOff;

}InspectionReportOption;

typedef struct
{
	bool InspectionResetOnRestart;
	bool QuickStartEnabled;
  bool AuditTrailButtonEnabled;
  bool FPGAVersionEnabled;
  bool AppButtonEnabled;
	int PrintModeOption;
	int PrintThreeDHeightOption;
	int MotorMinSpeed[3];
	int MotorMaxSpeed[3];
  int AjantaLocalNameNum;
  bool DHprogram;
  bool HIprogram;
  bool DHGradeHideProgram;
  bool SensorOutputSettingOption;
  bool SCADASystemSwitchEnabled;
  bool DetailRportView;
  bool IncludeUnInsTabletCount;
  bool PrintEQName;
  //한국콜마 2분배기.
  bool TwoSplitterEnable;
  //한국콜마 유유제약 분배기
  bool DistributorType1;
  bool DistributorType2;
  bool DistributorType3;
  bool DistributorType4;
  bool UVLaserEnabled;
  bool InitSubSamplingMode;
  bool ActiveResolutionSetting;
  bool UVLaserUpstreamEnabled;
  bool UVLaserDownstreamEnabled;
  WideString Nameofmachine;
  WideString MachineID;
  bool ApplyLSFTableSW;
  bool DistributorConveyerEnable;
  bool CareUpperLowCasePasswordEnabled;
  bool ResultGraphOpt;
  bool TcpIpMonitorActive;  
  InspectionReportOption InsRepOpt;
  bool CSV_PrintMaxPageChangeActive;
  int CSV_PrintMaxPageCnt; 
  int BackupSpeedMode;
  int PrintInsResUserDisplayOpt;
  bool AllAuthorityNotActive;
  bool VibratorFeederSpeedControlOpt;
  bool SendCompleteSigDistributor;
} TPCProgramOption;
extern TPCProgramOption PCProgramOption;

typedef struct
{
	TMESProductData TProductData;
	TMachineRunOption TMachineOption;
} eProductInfo;

typedef struct
{
	TMachineAlarmState TAlarmInfo_Machine;
} eAlarmInfo;

typedef struct
{
	TTabletGradeData TGradeData;
	TTabletInspectInfo TInspectInfomation;
	TInspectionOption TInspectOption;
  	TInspectionAdditionalInfo TInspectAddtionInfo;
} eParamInfo;


extern TUVLaserStatus UVLaser;
extern TNFALaserInfo NFALaserinfo;
extern eProductInfo MESUpDate_Product;
extern eParamInfo MESUpDate_Param;
extern eAlarmInfo MESUpDate_Alarm;

typedef struct
{
	char RecipeName[MAX_RECIPE_COUNT][MAX_RECIPE_NAME_SIZE];
	char RecipeDescription[MAX_RECIPE_COUNT][MAX_RECIPE_DESCRIPTION_SIZE];         //해당 배열에 디스크립션 데이터를 넣어주시면 됩니다. 
	char RecipeCount;
} TLaserInfo;
extern TLaserInfo RecipeInfo;

/**********************************/
//===== added by sjm TCPIP  1========
/**********************************/
typedef struct
{
	AnsiString ClientAddress1;
	AnsiString ClientAddress2;
} TIPAddressInfo;
extern TIPAddressInfo IPAddressInfo;

typedef struct
{
	AnsiString DualGoodTabletCount;
	AnsiString DualDefectTabletCount;
	AnsiString DualUnInsTabletCount;
	AnsiString DualTotalTabletCount;
} TDualRxTabletInsInfo;
extern TDualRxTabletInsInfo DualRxTabletInsInfo;

typedef struct
{
	AnsiString DualGoodTabletCount;
	AnsiString DualDefectTabletCount;
	AnsiString DualUnInsTabletCount;
	AnsiString DualTotalTabletCount;
} TDualTxTabletInsInfo;
extern TDualTxTabletInsInfo DualTxTabletInsInfo;

//sjm TCPIP
typedef struct
{
	unsigned int transaction_id1;
    unsigned int transaction_id2;
	unsigned int protocol_id1;
    unsigned int protocol_id2;
    unsigned int length1;
    unsigned int length2;
    unsigned int unit_id;
    String 		 function_code;
} TMODUS_HEAD;

typedef struct
{
	int boardExist;
}TTPBSystemInfo;

extern  TMODUS_HEAD MODUS_HEAD;
/**********************************/

extern TMachine Machine;

void __fastcall Environment_Init(void);
void __fastcall Environment_Destroy(void);

bool __fastcall SendSPBCaptureSetup_Multi(TProductData *pProductData,unsigned int globalCamMask, float tabletHalfLength, int *shutterSpeedList,
int disk1TargetSpeed, int disk1BaseSpeed, int disk2TargetSpeed, int disk2BaseSpeed,int TestSubsamplingMode, bool bCalib, int frameBufferCount = MAX_FRAME_BUFFER_COUNT, int triggerFreq_3D = 0);

bool __fastcall EnabledThreeDLaserSensor(int globalCameraIndex, int LSFValue, int calibrationMode);
bool __fastcall DisabledThreeDLaserSensor(int globalCameraIndex);
void __fastcall SendThreeDCameraSensorOnOffSignal(int SensorOn, int Disk1LSFValue, int Disk2LSFValue);

AnsiString __fastcall GetDefectDataPath(AnsiString productCode);
AnsiString __fastcall GetDefectDataPath(AnsiString productCode, AnsiString lotName);
AnsiString __fastcall GetProductImagePath(void);
AnsiString __fastcall GetProductDataFileName(AnsiString productCode);
AnsiString __fastcall GetUserMachineEnvDataFileName(void);
AnsiString __fastcall GetDefectImageContainerFileName(int imageIndex, AnsiString productCode, AnsiString lotName);
AnsiString __fastcall GetDefectDataContainerFileName(int imageIndex, AnsiString productCode, AnsiString lotName);

void __fastcall SaveDSMInfo(void);

void __fastcall ConnectCSVLogFile(void);
void __fastcall DisconnectCSVLogFile(void);
void __fastcall StopCSVLogFile(void);
void __fastcall ResumeCSVLogFile(void);

bool __fastcall AddCSVEventLog(ECSVEvent event, unsigned char *params, int paramSize);
bool __fastcall AddCSVActionLog(ECSVAction action, AnsiString userName, AnsiString productName, unsigned char *params, int paramSize);

bool __fastcall ReadComputerSystemInfo(AnsiString fileName, TComputerSystemInfo &computerSystemInfo);
void __fastcall WriteComputerSystemInfo(AnsiString fileName, TComputerSystemInfo &computerSystemInfo);

bool __fastcall BackupProductData(EProductDataBackupReason proudctDataBackupReason);
void __fastcall GetDataModificationInfo(TProductData DestProductData, bool *tabletInfoModified, bool *machineInfoModified, bool *inspectionInfoModified);
bool __fastcall ProductDataModified(void);

bool __fastcall ReadPCSystemHeader(AnsiString fileName);
void __fastcall WritePCSystemHeader(AnsiString fileName);

bool __fastcall ReadInitialValues(AnsiString fileName);
void __fastcall WriteInitialValues(AnsiString fileName);

bool __fastcall ReadPCProgramOption(AnsiString fileName, TPCProgramOption &pcProgramOption);
void __fastcall WritePCProgramOption(AnsiString fileName, TPCProgramOption &pcProgramOption);
void __fastcall WritePCProgram3DCameraOption(AnsiString fileName, TPCProgramOption &pcProgramOption);

bool __fastcall ExtractImage(Graphics::TBitmap *bitmap, int imageNumber, int globalCameraNumber, bool offsetSW, unsigned char *offsetImage, int SubSamplingMode, EImageKind imageKind = EIK_NORMAL);

bool __fastcall ExtractBayerImage(unsigned char *data, int imageNumber, int globalCameraNumber, EImageKind imageKind = EIK_NORMAL);
bool __fastcall ExtractProductImage(AnsiString productName, Graphics::TBitmap *bitmap, int imageNumber, int globalCameraNumber, EImageKind imageKind = EIK_NORMAL);

bool __fastcall ExtractImageFromContainer(Graphics::TBitmap *bitmap, AnsiString containerFileName, AnsiString bitmapName, bool offsetSW, unsigned char *offsetImage, int SamplingMode);
bool __fastcall ExtractImageDataFromContainer(unsigned char *data, AnsiString containerFileName, AnsiString bitmapName);

void ComponentSetFontName(TComponent *pComponent, const AnsiString aFontName);
void ComponentSetMultiLine(TComponent *pComponent);

int __fastcall CameraIndexSubstitutionForTest(int cameraIndex);

void __fastcall RefreshCameraInfoForInspectionSetting(TProductData *productData, int ShutterSpeed, int writeMask, int camIndex, bool *cameraEnabled, bool bROIDefault);

bool __fastcall Read3DCameraDefaultInformation(AnsiString fileName, int cameraIndex);
bool __fastcall Write3DCameraDefaultInformation(AnsiString fileName, int cameraIndex);

TROIInfo __fastcall ReadCameraInformation(AnsiString fileName, int cameraIndex);
bool __fastcall WriteCameraInformation(AnsiString fileName, int cameraIndex);

bool __fastcall SetCameraInformation(TROIInfo ROIInfo, int ShutterSpeed, int ThresholdFor3D,int SubSamplingMode, int cameraIndex, int wMask);

TCommDataLength eMakeCameraDataPacket(char *code, int cameraIndex, int dataIndex);
bool __fastcall RequestCameraCommand(char *sendData, char *receivedData, unsigned int SendDataLength, unsigned int ReceiveDataLength, int cameraIndex);


TROIInfo __fastcall SetThreeDCameraROI(TROIInfo srcInfo, TProductData *productData);

void ComponentSetEnabledStatus(TComponent *pComponent, bool bEnabled);
void __fastcall GetNFACamera2DColorImage(Graphics::TBitmap *DstImage, unsigned char *srcImage, int ImageWidth, int ImageHeight, int cameraIndex, bool offsetSW, unsigned char *offsetImage, int SamplingMode);

bool __fastcall ReadGlobalLSFTable(AnsiString fileName);
bool __fastcall ReadCameraID(AnsiString fileName);
bool __fastcall IsExistProcess(AnsiString ProcessName);

extern bool bSystemStatusCheckSW;
extern int RANGER_3D_BASE_SHUTTER_SPEED;// 1번 3D
extern int RANGER_3D_BASE_SHUTTER_SPEED2;// 2번 3D

extern int GlobalSD1LSFTable[MAX_MOTOR_SPEED];
extern int GlobalSD2LSFTable[MAX_MOTOR_SPEED];

extern int SYSTEM_DEFAULT_ANLOG_GAIN;

extern TTPBSystemInfo TPBSystemInfo;

void __fastcall _CreateReg(const char* PATH ,const char* ID);
int __fastcall _SetValueReg(const char* PATH ,const char* ID , int value);
void __fastcall _DeleteReg(const char* PATH ,const char* ID);
int __fastcall _ReadReg(const char* PATH,const char* ID);
int __fastcall _IDUnlockCheckReg(const char* PATH,const char* ID);
bool __fastcall checkCameraArea(TProductData *pProductData, bool *pErrorCamera);
bool __fastcall WritePCProgramErrorLog(AnsiString ClassNamem, int ErrorLine);
bool __fastcall ReductionImageScale(Graphics::TBitmap *bitmap);
void __fastcall _SetKeyHookReg(const char* First_PATH , const char* Second_PATH ,bool AccessState);
void __fastcall KeyMonitorActive(bool DestoryOption=false);
void __fastcall WriteBackupProgramOption(AnsiString fileName, TPCProgramOption &pcProgramOption);

void __fastcall InitQueryTime();
void __fastcall WriteProcessingBeginTime();
void __fastcall WriteProcessingEndTime();
double __fastcall GetProcessingElapsedTime();
void __fastcall WriteCheckBeginTime();
void __fastcall WriteCheckEndTime();
double __fastcall GetCheckElapsedTime(int mode); // 0 = 체크 시작과 끝 사이. 1 = 전체 시작과 체크 시작 사이. 2 = 체크 끝과 전체 끝 사이.

void __fastcall ShowHintByName(TWinControl *winControl);

#endif

