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

#include <vcl.h>
#pragma hdrstop

#include "AuditTrail_Form.h"
#include "Environment.h"
#include "Message_Form.h"
#include "Keyboard_Form.h"
#include "CalendarDialog_Form.h"
#include "MultiLanguage.h"
#include "PrintAuditTrail_Form.h"
#include "PrintAuditTrail_Ajanta_Form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntExtCtrls"
#pragma link "TntGrids"
#pragma link "TntStdCtrls"
#pragma link "TntComCtrls"
#pragma resource "*.dfm"
TAuditTrailForm* AuditTrailForm;
//---------------------------------------------------------------------------
__fastcall TAuditTrailForm::TAuditTrailForm(TComponent* Owner)
	: TTntForm(Owner)
{
	if (DefaultLCID == 1028 || DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
		ComponentSetFontName(this, "SimSun");
	else if (DefaultLCID == 1041)
		ComponentSetFontName(this, "Meiryo UI");
	else if (DefaultLCID == 3082)
	{
		ComponentSetFontName(this, "Segoe UI");
		ComponentSetMultiLine(this);
	}

	GetDefaultString();
	CSVLogList = new TCSVLogList;
	RowToDataMap = NULL;
	AlarmOnlyCheckBox->Enabled = false;
	PrintButton->Enabled = false;

}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::GetDefaultString()
{
	BrowseButton->Caption = AUDITTRAILFORM_BUTTON_CAPTION_01;
	BrowseStartDateButton->Caption = AUDITTRAILFORM_BUTTON_CAPTION_02;
	BrowseEndDataButton->Caption = AUDITTRAILFORM_BUTTON_CAPTION_02;
	PeriodButton4->Caption = AUDITTRAILFORM_BUTTON_CAPTION_03;
	PeriodButton2->Caption = AUDITTRAILFORM_BUTTON_CAPTION_04;
	PeriodButton1->Caption = AUDITTRAILFORM_BUTTON_CAPTION_05;
	PeriodButton3->Caption = AUDITTRAILFORM_BUTTON_CAPTION_06;
	PrintButton->Caption = AUDITTRAILFORM_BUTTON_CAPTION_07;
	ActionKindCheckBox->Caption = AUDITTRAILFORM_CHECKBOX_CAPTION_01;
	EventKindCheckBox->Caption = AUDITTRAILFORM_CHECKBOX_CAPTION_02;
	AlarmOnlyCheckBox->Caption = AUDITTRAILFORM_CHECKBOX_CAPTION_03;
	this->Caption = AUDITTRAILFORM_FORM_CAPTION_01;
	GroupBox2->Caption = AUDITTRAILFORM_GROUPBOX_CAPTION_01;
	GroupBox1->Caption = AUDITTRAILFORM_GROUPBOX_CAPTION_02;
	GroupBox4->Caption = AUDITTRAILFORM_GROUPBOX_CAPTION_03;
	Label1->Caption = AUDITTRAILFORM_LABEL_CAPTION_01;
	Label3->Caption = AUDITTRAILFORM_LABEL_CAPTION_02;

	GroupBox3->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_01;
	AllUserRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_02;
	AllProductRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_03;
	SpecifiedUserRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_04;
	SpecifiedProductRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_05;
	CurrentUserRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_06;
	CurrentProductRadioButton->Caption = AUDITTRAILFORM_RADIOBTN_CAPTION_07;

	//add
	CloseButton->Caption = MACHINESETTINGTESTFORM_BUTTON_CAPTION_16;

}
void __fastcall TAuditTrailForm::BrowseButtonClick(TObject* Sender)
{
	bool unReadFileExist;

	CSVLogList->Clear();

	unsigned short year;
	unsigned short month;
	unsigned short day;
	Now().DecodeDate(&year, &month, &day);

	StopCSVLogFile();


	AnsiString logPath = ProgramPath.Log + "\\CSV Log\\";
	TSearchRec sr;
	int iAttributes = faAnyFile;
	unReadFileExist = false;
	if (FindFirst(logPath + "\\*.clg", iAttributes, sr) == 0)
	{
		do
		{
			AnsiString filename = logPath + "\\" + sr.Name;
			TFileStream* fileStream = new TFileStream(filename, fmOpenReadWrite);
			try
			{
				CSVLogList->LoadFromFileStream(fileStream, filename, BrowseStartTime, BrowseEndTime);
			}
			catch (CSVLogException& ec)
			{
				unReadFileExist = true;
			}
			delete fileStream;
		} while (FindNext(sr) == 0);
		FindClose(sr);
	}

	if (unReadFileExist)
	{
		ShowMessageFA(AUDITTRAILFORM_MSG_01);
	}
	else
		PrintButton->Enabled = true;

	DrawStringGrid();

	ResumeCSVLogFile();
	/*
		while (true)
		{
			AnsiString dateStr = Format("%.4d-%.2d-%.2d-%.4d", ARRAYOFCONST((year, month, day, logFileIndex)));
			newFileName = ProgramPath.Log + "\\CSV Log\\" + dateStr + ".clg";
			if (!FileExists(newFileName))
			{
				break;
			}
			else
			{
				lastFileName = newFileName;
				logFileIndex++;
			}
		}
		if (lastFileName == "")
		{
			TCSVLogFileHeader *csvLogFileHeader = new TCSVLogFileHeader(Now().Val);
			LogFileStream = new TFileStream(newFileName, fmCreate);
			csvLogFileHeader->SaveToFileStream(LogFileStream);
			delete csvLogFileHeader;
		}
		else
		{
			LogFileStream = NULL;
			TCSVLogFileHeader *csvLogFileHeader = NULL;
			try
			{
				LogFileStream = new TFileStream(lastFileName, fmOpenReadWrite);
				csvLogFileHeader = new TCSVLogFileHeader(Now().Val);
				csvLogFileHeader->LoadFromFileStream(LogFileStream);
				delete csvLogFileHeader; csvLogFileHeader = NULL;
				LogFileStream->Seek(LogFileStream->Size, soFromBeginning);
			}
			catch (CSVLogException &ec)
			{
				ShowMessageW(ec.Message);
				if (LogFileStream) delete LogFileStream;
				if (csvLogFileHeader) delete csvLogFileHeader;

				TCSVLogFileHeader *csvLogFileHeader = new TCSVLogFileHeader(Now().Val);
				LogFileStream = new TFileStream(newFileName, fmCreate);
				csvLogFileHeader->SaveToFileStream(LogFileStream);
				delete csvLogFileHeader; csvLogFileHeader = NULL;
			}
			catch (Exception &ec)
			{
				ShowMessageW(ec.Message);
			}
		}
	//
	*/

	LogReportStringGridClick(LogReportStringGrid);
}
//------------------------------------------------------------------------
void __fastcall TAuditTrailForm::OnUserChange(void)
{
	if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_MAINFORM_AUDIT_TRAIL])
	{
		CloseButton->Click();
	}
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::FormClose(TObject* Sender,
	TCloseAction& Action)
{
	delete CSVLogList;
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::ClearReportStringGrid(void)
{
	LogReportStringGrid->RowCount = 2;

	LogReportStringGrid->Cells[0][0] = "No.";
	LogReportStringGrid->Cells[1][0] = AUDITTRAILFORM_STRGRID_CELL_04;
	LogReportStringGrid->Cells[2][0] = AUDITTRAILFORM_STRGRID_CELL_02;
	LogReportStringGrid->Cells[3][0] = AUDITTRAILFORM_STRGRID_CELL_03;
	LogReportStringGrid->Cells[4][0] = AUDITTRAILFORM_STRGRID_CELL_05;
	LogReportStringGrid->Cells[5][0] = AUDITTRAILFORM_STRGRID_CELL_01;

	for (int col = 0; col < LogReportStringGrid->ColCount; col++)
	{
		LogReportStringGrid->Cells[col][1] = "";
	}
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::FormCreate(TObject* Sender)
{
	LogReportStringGrid->ColWidths[0] = 48;
	LogReportStringGrid->ColWidths[1] = 70;
	LogReportStringGrid->ColWidths[2] = 170;
	LogReportStringGrid->ColWidths[3] = 100;
	LogReportStringGrid->ColWidths[4] = 100;
	LogReportStringGrid->ColWidths[5] = 1100;

	BrowseStartTime = Now();
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();

	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();
	StartDateTime = BrowseStartTime.DateString() + " " + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	EndDateTime = BrowseEndTime.DateString() + " " + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();

	DetailInfoMemo->Visible = true;
	ClearReportStringGrid();
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::LogReportStringGridClick(TObject* Sender)
{
	if (LogReportStringGrid->Row > 0)
	{
		int rowIndex = LogReportStringGrid->Row;
		if (rowIndex <= CSVLogList->DataCount)
		{
			if (!LogReportStringGrid->Cells[1][LogReportStringGrid->Row].IsEmpty())
			{
				CSVLogList->GetDetailInfo(RowToDataMap[rowIndex], DetailInfoMemo->Lines);

				TDateTime SelectedLogTime = CSVLogList->GetTimeInfo(RowToDataMap[rowIndex]);
				MonthCalendar->Date = SelectedLogTime;

				unsigned short hour, min, sec, msec;
				SelectedLogTime.DecodeTime(&hour, &min, &sec, &msec);
				HourEdit->Text = IntToStr(hour);
				MinEdit->Text = IntToStr(min);
				SecEdit->Text = IntToStr(sec);
			}
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::PeriodButton1Click(TObject* Sender)
{
	BrowseStartTime.Val = Now().Val - 7;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();

	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::PeriodButton2Click(TObject* Sender)
{
	BrowseStartTime.Val = Now().Val - 30;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();

	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::PeriodButton3Click(TObject* Sender)
{
	BrowseStartTime.Val = Now().Val - 90;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();

	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::PeriodButton4Click(TObject* Sender)
{
	BrowseStartTime.Val = 0;
	BrowseEndTime = Now();
	BrowseStartDateLabel->Caption = "~";
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();

	if (!CheckDateTime(0, 0))
	{
		ShowMessageFA("Wrong time setting");
	}
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::DrawStringGrid(void)
{
	ClearReportStringGrid();

	int dataCount = CSVLogList->DataCount;
	if (RowToDataMap) { delete[] RowToDataMap; RowToDataMap = NULL; }

	if (dataCount <= 0)
	{
		LogReportStringGrid->RowCount = 2;
	}
	else
	{
		RowToDataMap = new int[dataCount + 1];
		LogReportStringGrid->RowCount = dataCount + 1;
		WideString productName = "";
		AnsiString creatorName = "";
		if (AllProductRadioButton->Checked)
		{
			productName = "";
			ProductName = "";
		}
		else if (CurrentProductRadioButton->Checked)
		{
			productName = ProductData.ProductName;
			ProductName = ProductData.ProductName;
		}
		else
		{
			productName = ProductNameEdit->Text;
			ProductName = ProductNameEdit->Text;
		}

		if (AllUserRadioButton->Checked)
		{
			creatorName = "";
			CreatorName = "";
		}
		else if (CurrentUserRadioButton->Checked)
		{
			creatorName = UserInfo.Name;
			CreatorName = UserInfo.Name;
		}
		else
		{
			creatorName = UserNameEdit->Text;
			CreatorName = UserNameEdit->Text;
		}

		int rowIndex = 1;
		ValidData = 0;
		for (int dataIndex = 0; dataIndex < dataCount; dataIndex++)
		{
			bool dataValid = true;
			ECSVLogKind kind = CSVLogList->GetKind(dataIndex);
			if ((kind == ECSV_LOG_KIND_EVENT && EventKindCheckBox->Checked) ||
				(kind == ECSV_LOG_KIND_ACTION && ActionKindCheckBox->Checked))
			{
				dataValid = true;
			}
			else
			{
				dataValid = false;
			}


			if (!productName.IsEmpty())
			{
				WideString Name = CSVLogList->GetProductName(dataIndex);
				int n_Length = Name.Length();
				if (n_Length == 0)
				{
					dataValid = false;
				}
				else
				{
					int p_Length = productName.Length();

					if (p_Length == n_Length)
					{
						WideString LogProductName = Name;
						WideString InputProductName = productName;
						if (_tcscmp(_tcslwr(LogProductName), _tcslwr(InputProductName)) == 0)
							dataValid = true;
						else
							dataValid = false;
					}
					else
					{
						int p_nameIndex = 0;
						for (int i = 0; i < n_Length; ++i)
						{
							if (p_nameIndex > p_Length) p_nameIndex -= 1;
							WideString LogProductName = Name;
							WideString InputProductName = productName;
							if (p_nameIndex > 0 && _tcslwr(LogProductName)[i] == _tcslwr(InputProductName)[p_nameIndex])
							{
								if (p_nameIndex == p_Length)
									break;
							}
							/*else if(p_nameIndex > 0)
							{
								p_nameIndex = 0;
									continue;
							} */

							LogProductName = Name;
							InputProductName = productName;

							if (_tcslwr(LogProductName)[i] == _tcslwr(InputProductName)[p_nameIndex])
								p_nameIndex++;
						}

						if (p_nameIndex == p_Length)
						{
							dataValid = true;
						}
						else
							dataValid = false;
					}

				}

			}
			if (dataValid == true)
			{
				if (creatorName != "")
				{
					AnsiString Name = CSVLogList->GetCreatorName(dataIndex);
					int n_Length = Name.Length();
					if (Name == 0)
					{
						dataValid = false;
					}
					else
					{
						int c_Length = creatorName.Length();
						if (c_Length == n_Length)
						{
							if (CreatorName.LowerCase() == Name.LowerCase())
								dataValid = true;
							else
								dataValid = false;
						}
						else
						{
							int c_nameIndex = 0;
							for (int i = 0; i < n_Length; ++i)
							{
								if (c_nameIndex > c_Length) c_nameIndex -= 1;
								if (c_nameIndex > 0 && Name.LowerCase().c_str()[i] != creatorName.LowerCase().c_str()[c_nameIndex])
								{
									if (c_nameIndex == c_Length)
										break;
								}

								if (Name.LowerCase().c_str()[i] == creatorName.LowerCase().c_str()[c_nameIndex])
									c_nameIndex++;
							}

							if (c_nameIndex == c_Length)
								dataValid = true;
							else
								dataValid = false;

						}
					}
				}
			}

			//cik add 알람만 표시하기 위한 동작
			if (AlarmOnlyCheckBox->Checked)
			{
				if (kind == ECSV_LOG_KIND_ACTION)
				{
					dataValid = false;
				}

				if (kind == ECSV_LOG_KIND_EVENT)
				{
					ECSVEvent temp = CSVLogList->GetEventKind(dataIndex);
					if (temp != ECSV_EVENT_ALARM && temp != ECSV_EVENT_ALARM_CLEAR)
					{
						dataValid = false;
					}
				}
			}
			TDateTime date = CSVLogList->GetTimeInfo(dataIndex);
			double diffStart, diffEnd;
			diffStart = StartDateTime - date;
			if (diffStart > 0)
				dataValid = false;

			diffEnd = date - EndDateTime;
			if (diffEnd > 0)
				dataValid = false;

			if (dataValid)
			{
				LogReportStringGrid->Cells[0][rowIndex] = IntToStr(rowIndex);
				LogReportStringGrid->Cells[1][rowIndex] = CSVLogList->GetKindStr(dataIndex);
				LogReportStringGrid->Cells[2][rowIndex] = CSVLogList->GetTimeStr(dataIndex);
				LogReportStringGrid->Cells[3][rowIndex] = CSVLogList->GetCreatorName(dataIndex);
				LogReportStringGrid->Cells[4][rowIndex] = CSVLogList->GetProductName(dataIndex);
				LogReportStringGrid->Cells[5][rowIndex] = CSVLogList->GetMessage(dataIndex);

				if (LogReportStringGrid->Cells[5][rowIndex].Length() > 15)
					LogReportStringGrid->Cells[5][rowIndex].Insert(L"\r\n", 10);
				RowToDataMap[rowIndex] = dataIndex;
				rowIndex++;
				ValidData++;
			}
		}
		if (rowIndex == 1)
		{
			LogReportStringGrid->RowCount = 2;
		}
		else
		{
			LogReportStringGrid->RowCount = rowIndex;
		}
	}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::NumberEditClick(TObject* Sender)
{
	TTntEdit* theEdit = (TTntEdit*)Sender;
	unsigned short year, month, day, Starthour, Startmin, Endhour, Endmin;
	int time;
	TDateTime start, end;
	double diff;

	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeyboard() == mrOk)
	{
		if (theEdit->Tag == 0)
		{
			theEdit->Text = KeyboardForm->Text;
			return;
		}

		time = StrToInt(KeyboardForm->Text);
		switch (theEdit->Tag)
		{
		case 1:
			if (time > 23)
			{
				ShowMessageFA("Wrong start hour");
				return;
			}
			Starthour = time;
			Startmin = StrToInt(BrowseStartMinEdit->Text);
			Endhour = StrToInt(BrowseEndHourEdit->Text);
			Endmin = StrToInt(BrowseEndMinEdit->Text);
			break;

		case 2:
			if (time > 59)
			{
				ShowMessageFA("Wrong start minute");
				return;
			}
			Starthour = StrToInt(BrowseStartHourEdit->Text);
			Startmin = time;
			Endhour = StrToInt(BrowseEndHourEdit->Text);
			Endmin = StrToInt(BrowseEndMinEdit->Text);
			break;

		case 3:
			if (time > 23)
			{
				ShowMessageFA("Wrong end hour");
				return;
			}
			Starthour = StrToInt(BrowseStartHourEdit->Text);
			Startmin = StrToInt(BrowseStartMinEdit->Text);
			Endhour = time;
			Endmin = StrToInt(BrowseEndMinEdit->Text);
			break;

		case 4:
			if (time > 59)
			{
				ShowMessageFA("Wrong end minute");
				return;
			}
			Starthour = StrToInt(BrowseStartHourEdit->Text);
			Startmin = StrToInt(BrowseStartMinEdit->Text);
			Endhour = StrToInt(BrowseEndHourEdit->Text);
			Endmin = time;
			break;
		}

		BrowseStartTime.DecodeDate(&year, &month, &day);
		start = TDateTime(year, month, day) + TDateTime(Starthour, Startmin, 0, 0);

		BrowseEndTime.DecodeDate(&year, &month, &day);
		end = TDateTime(year, month, day) + TDateTime(Endhour, Endmin, 0, 0);

		diff = end - start;
		if (diff <= 0)
		{
			ShowMessageFA("Wrong time setting");
			return;
		}

		theEdit->Text = KeyboardForm->Text;
	}

}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::BrowseStartDateButtonClick(
	TObject* Sender)
{
	TCalendarDialogForm* calendarDialogForm = new TCalendarDialogForm(this);
	if (mrOk == calendarDialogForm->ShowModal())
	{
		if (!CheckDateTime(calendarDialogForm->MonthCalendar->Date, 0))
		{
			ShowMessageFA("Wrong time setting");
			return;
		}
		BrowseStartTime = calendarDialogForm->MonthCalendar->Date;
	}
	delete calendarDialogForm;
	BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
	BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();

	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::BrowseEndDataButtonClick(TObject* Sender)
{
	TCalendarDialogForm* calendarDialogForm = new TCalendarDialogForm(this);
	if (mrOk == calendarDialogForm->ShowModal())
	{
		if (!CheckDateTime(0, calendarDialogForm->MonthCalendar->Date))
		{
			ShowMessageFA("Wrong time setting");
			return;
		}
		BrowseEndTime = calendarDialogForm->MonthCalendar->Date;
	}
	delete calendarDialogForm;
	BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
	BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();

	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::FormDestroy(TObject* Sender)
{
	if (RowToDataMap) { delete[] RowToDataMap; RowToDataMap = NULL; }
}
//---------------------------------------------------------------------------



void __fastcall TAuditTrailForm::EventKindCheckBoxClick(TObject* Sender)
{
	if (EventKindCheckBox->Checked)
	{
		AlarmOnlyCheckBox->Enabled = true;
	}
	else
	{
		AlarmOnlyCheckBox->Enabled = false;
		AlarmOnlyCheckBox->Checked = false;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::BackupButtonClick(TObject* Sender)
{
	unsigned short year;
	unsigned short month;
	unsigned short day;
	AnsiString tempStr, srcPath, dirPath;
	int idx, logCnt, iAttributes, result;
	TSearchRec sr;
	bool unReadFileExist, failToWrite;

	Now().DecodeDate(&year, &month, &day);
	StopCSVLogFile();

	tempStr = IntToStr(year) + IntToStr(month) + IntToStr(day) + "\\";
	//dirPath = ProgramPath.Log + "\\CSV Log Backup\\" + tempStr;

	if (SelectDirectory("Select a directory", "", dirPath))
	{
		dirPath += "\\" + tempStr;

		if (!DirectoryExists(dirPath))
			ForceDirectories(dirPath);

		iAttributes = faAnyFile;
		srcPath = ProgramPath.Log + "\\CSV Log\\";
		failToWrite = unReadFileExist = false;
		if (FindFirst(srcPath + "\\*.clg", iAttributes, sr) == 0)
		{
			do
			{
				TFileStream* fileStreamRead = new TFileStream(srcPath + "\\" + sr.Name, fmOpenRead);
				try
				{
					unsigned char* buffer = new unsigned char[fileStreamRead->Size];
					fileStreamRead->Read(&buffer[0], fileStreamRead->Size * sizeof(unsigned char));

					TFileStream* fileStreamWrite = new TFileStream(dirPath + sr.Name, fmCreate);
					result = fileStreamWrite->Write(&buffer[0], fileStreamRead->Size * sizeof(unsigned char));
					delete[] buffer;
					delete fileStreamWrite;

					if (!result)
					{
						failToWrite = true;
						break;
					}
				}
				catch (CSVLogException& ec)
				{
					failToWrite = true;
					unReadFileExist = true;
				}
				delete fileStreamRead;
			} while (FindNext(sr) == 0);
			FindClose(sr);
		}

		if (failToWrite)
		{
			AnsiString tmpStr = AUDITTRAILFORM_MESSAGE_01;
			ShowMessage(tmpStr);
		}
		else
		{
			AnsiString tmpStr = AUDITTRAILFORM_MESSAGE_02;
			ShowMessage(tmpStr);
		}
	}

	ResumeCSVLogFile();
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::PrintButtonClick(TObject* Sender)
{
	if (!ValidData)
		return;

	bool bLimitLog = false;
	bool bCancel = false;
	int startLogIndex, endLogIndex, MAX_PrintIndex;

	WCHAR tempString[100];

	if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
		MAX_PrintIndex = 15 + (25 * 10);
	else
	{
		if(PCProgramOption.CSV_PrintMaxPageChangeActive)
		{
//#define MAX_PRINT_LOG_INDEX (MAX_PRINT_PAGE_INDEX * MAX_CSV_LOG_INDEX) + 19		
			MAX_PrintIndex = ((PCProgramOption.CSV_PrintMaxPageCnt - 1) * MAX_CSV_LOG_INDEX) + 19;
		}
		else
		{
			MAX_PrintIndex = MAX_PRINT_LOG_INDEX;
		}
	}

	if (LogReportStringGrid->RowCount > MAX_PrintIndex)
	{
		if (MessageDlgFA(AUDITTRAILFORM_MSG_02, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
		{
			MessageDlgFA(AUDITTRAILFORM_MSG_03, mtConfirmation, TMsgDlgButtons() << mbOK);

			if (KeyboardForm->ShowKeypad() == mrOk)
			{
				startLogIndex = StrToInt(KeyboardForm->Text);

				if (startLogIndex < 1) startLogIndex = 1;
				if (startLogIndex > LogReportStringGrid->RowCount - 1) startLogIndex = LogReportStringGrid->RowCount - 1;

				int maxLogIndex;
				//maxLogIndex = min(LogReportStringGrid->RowCount, startLogIndex + MAX_PRINT_LOG_INDEX);
				maxLogIndex = min(LogReportStringGrid->RowCount, startLogIndex + MAX_PrintIndex);

				wsprintfW(tempString, AUDITTRAILFORM_MSG_04, maxLogIndex - 1);
				MessageDlgFA(tempString, mtConfirmation, TMsgDlgButtons() << mbOK);

				while (1)
				{
					if (KeyboardForm->ShowKeypad() == mrOk)
					{
						endLogIndex = StrToInt(KeyboardForm->Text);

						if (endLogIndex < 1) startLogIndex = 1;
						if (endLogIndex > LogReportStringGrid->RowCount - 1) endLogIndex = LogReportStringGrid->RowCount - 1;

						if (endLogIndex < startLogIndex) endLogIndex = startLogIndex;

						//if (endLogIndex - startLogIndex >= MAX_PRINT_LOG_INDEX)
						if (endLogIndex - startLogIndex >= MAX_PrintIndex)
						{
							wsprintfW(tempString, AUDITTRAILFORM_MSG_05, maxLogIndex);
							MessageDlgFA(tempString, mtConfirmation, TMsgDlgButtons() << mbOK);
						}
						else
						{
							ValidData = (endLogIndex - startLogIndex) + 1;

							startLogIndex = RowToDataMap[startLogIndex];
							endLogIndex = RowToDataMap[endLogIndex];

							bLimitLog = true;
							break;
						}
					}
					else
					{
						bCancel = true;
						break;
					}
				}
			}
			else
			{
				bCancel = true;
			}
		}
		else
		{
			bCancel = true;
		}
	}

	if (bCancel) return;

	ComponentSetEnabledStatus(this, false);

	if (MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
	{
		PrintAuditTrail_Ajanta_Form = new TPrintAuditTrail_Ajanta_Form(this);

		PrintAuditTrail_Ajanta_Form->SetReport(CSVLogList, ValidData, ActionKindCheckBox->Checked, EventKindCheckBox->Checked, AlarmOnlyCheckBox->Checked,
			(double)StartDateTime, (double)EndDateTime, startLogIndex, endLogIndex, bLimitLog, ProductName, CreatorName);
		PrintAuditTrail_Ajanta_Form->Show();
	}
	else
	{
		PrintAuditTrailForm = new TPrintAuditTrailForm(this);
		PrintAuditTrailForm->SetReport(CSVLogList, ValidData, ActionKindCheckBox->Checked, EventKindCheckBox->Checked, AlarmOnlyCheckBox->Checked, (double)StartDateTime, (double)EndDateTime, startLogIndex, endLogIndex, bLimitLog, ProductName, CreatorName);
		PrintAuditTrailForm->ShowModal();
	}
	ComponentSetEnabledStatus(this, true);
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::BrowseEditChange(TObject* Sender)
{
	double diff;
	int nStartHour, nStartMin, nEndHour, nEndMin;
	unsigned short year, month, day;

	BrowseStartTime.DecodeDate(&year, &month, &day);
	StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	BrowseEndTime.DecodeDate(&year, &month, &day);
	EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);

	BrowseStartTimeLabel->Caption = StartDateTime.TimeString();
	BrowseEndTimeLabel->Caption = EndDateTime.TimeString();
}
//---------------------------------------------------------------------------
bool __fastcall TAuditTrailForm::CheckDateTime(TDateTime StartDate, TDateTime EndDate)
{
	double diff;
	TDateTime start, end;
	unsigned short year, month, day;
	int time;

	time = StrToInt(BrowseStartHourEdit->Text);
	if (time > 23)
	{
		ShowMessageFA("Wrong start hour");
		return false;
	}

	time = StrToInt(BrowseStartMinEdit->Text);
	if (time > 59)
	{
		ShowMessageFA("Wrong start minute");
		return false;
	}

	time = StrToInt(BrowseEndHourEdit->Text);
	if (time > 23)
	{
		ShowMessageFA("Wrong end hour");
		return false;
	}

	time = StrToInt(BrowseEndMinEdit->Text);
	if (time > 59)
	{
		ShowMessageFA("Wrong end minute");
		return false;
	}

	if (!StartDate.Val)
		StartDate = BrowseStartTime;
	StartDate.DecodeDate(&year, &month, &day);
	start = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

	if (!EndDate.Val)
		EndDate = BrowseEndTime;
	EndDate.DecodeDate(&year, &month, &day);
	end = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 0, 0);

	diff = end - start;
	if (diff <= 0)
	{
		ShowMessageFA("Wrong time setting");
		return false;
	}

	return true;
}
//-------------------------------------------------------------------------------------------------------------------------
void __fastcall TAuditTrailForm::TntFormShow(TObject* Sender)
{
	if (ProductData.ProductName.IsEmpty())
		CurrentProductRadioButton->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::ProductNameEditClick(TObject* Sender)
{
	TTntEdit* theEdit = (TTntEdit*)Sender;

	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeyboard() == mrOk)
	{
		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::TntFormActivate(TObject* Sender)
{
	SetScreenPosition(this);
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::Panel2DblClick(TObject* Sender)
{
	KeyboardForm->Text = "";
	if (LogChangeGroupBox->Visible == false)
	{
		if (KeyboardForm->ShowPasswordKeyboard() == mrOk)
		{
			if (AnsiString(KeyboardForm->Text).LowerCase() == "nfa@9500!sw")
			{
				LogChangeGroupBox->Visible = true;
				EventKindCheckBox->Checked = true;
				BrowseButtonClick(BrowseButton);
        pnCSV_Option->Visible = true;
			}
			else
			{
				ShowMessage("비밀번호가 일치하지 않습니다.");
			}

      KeyboardForm->Text = "";
		}
	}
	else
	{
		LogChangeGroupBox->Visible = false;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::HourEditClick(TObject* Sender)
{
	TTntEdit* theEdit = (TTntEdit*)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeypad() == mrOk)
	{
		try
		{
			int val = StrToInt(KeyboardForm->Text);

			if (theEdit->Tag == 0)
			{
				if (val < 0 || val >= 24)
				{
					ShowMessage("입력범위 벗어남. [0 - 23]");
					return;
				}
			}
			else if (theEdit->Tag == 1 || theEdit->Tag == 2)
			{
				if (val < 0 || val >= 60)
				{
					ShowMessage("입력범위 벗어남. [0 - 59]");
					return;
				}
			}
		}
		catch (...)
		{
			ShowMessage("입력값 에러");
			return;
		}

		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::LogTimeChangeButtonClick(TObject* Sender)
{
  int rowIndex = LogReportStringGrid->Row;
  if (rowIndex <= CSVLogList->DataCount)
  {
    if(!LogReportStringGrid->Cells[1][LogReportStringGrid->Row].IsEmpty())
    {
      TDateTime nDate = MonthCalendar->Date;
      TDateTime nTime = TDateTime(StrToInt(HourEdit->Text), StrToInt(MinEdit->Text), StrToInt(SecEdit->Text), 0);

      TDateTime nLogTime = nDate + nTime;
      TDateTime SelectedLogTime = CSVLogList->GetTimeInfo(RowToDataMap[rowIndex]);

      int prevDataIndex = RowToDataMap[rowIndex] - 1;
      while(1)
      {
        if(prevDataIndex < 0) break;
        
        TDateTime neighborLogTime = CSVLogList->GetTimeInfo(prevDataIndex);

        if(neighborLogTime.Val == CSV_DELETE_LOG_TIME)
        {
          prevDataIndex--;
        }
        else
        {
          break;
        }
      }
      int nextDataIndex = RowToDataMap[rowIndex] + 1;
      while(1)
      {
        if(nextDataIndex > CSVLogList->DataCount - 1) break;
        
        TDateTime neighborLogTime = CSVLogList->GetTimeInfo(nextDataIndex);

        if(neighborLogTime.Val == CSV_DELETE_LOG_TIME)
        {
          nextDataIndex++;
        }
        else
        {
          break;
        }
      }
      
      if(prevDataIndex >= 0)
      {
        TDateTime neighborLogTime = CSVLogList->GetTimeInfo(prevDataIndex);
        if(neighborLogTime.Val >= nLogTime.Val)
        {
          ShowMessage("변경할 Log 시간은 이전 Log 시간보다 커야합니다.");
          return;
        }
      }

      if(nextDataIndex <= CSVLogList->DataCount - 1)
      {
        TDateTime neighborLogTime = CSVLogList->GetTimeInfo(nextDataIndex);
        if(neighborLogTime.Val <= nLogTime.Val)
        {
          ShowMessage("변경할 Log 시간은 다음 Log 시간보다 작아야합니다.");
          return;
        }
      }

      TDateTime diffDate = abs(SelectedLogTime - nLogTime);
      if(diffDate.Val >= 7) // 일주일
      {
        ShowMessage("변경 일자가 7일 이상인 경우 수정이 불가합니다.");
        return;
      }
      else
      {
        if(nLogTime < BrowseStartTime)
        {
          BrowseStartTime = nLogTime;
        }

        if(nLogTime > BrowseEndTime)
        {
          BrowseEndTime = nLogTime;
        }

        BrowseStartDateLabel->Caption = BrowseStartTime.DateString();
        BrowseStartTimeLabel->Caption = TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0).TimeString();

        BrowseEndDateLabel->Caption = BrowseEndTime.DateString();
        BrowseEndTimeLabel->Caption = TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59).TimeString();

        unsigned short year, month, day;

        BrowseStartTime.DecodeDate(&year, &month, &day);
        StartDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseStartHourEdit->Text), StrToInt(BrowseStartMinEdit->Text), 0, 0);

        BrowseEndTime.DecodeDate(&year, &month, &day);
        EndDateTime = TDateTime(year, month, day) + TDateTime(StrToInt(BrowseEndHourEdit->Text), StrToInt(BrowseEndMinEdit->Text), 59, 59);
      }

      AnsiString StreamFileName = CSVLogList->GetLogFileName(RowToDataMap[rowIndex]);

      if(FileExists(StreamFileName))
      {
        StopCSVLogFile();
        bool bRefresh = SearchAndRevisionLogFile(StreamFileName, SelectedLogTime, nLogTime, 0);
        ResumeCSVLogFile();

        if(bRefresh)
        {
          BrowseButtonClick(BrowseButton);
        }
      }
    }
    else
    {
      ShowMessage("선택된 LOG가 존재하지 않습니다.");
      return;
    }
  }
  else
  {
    ShowMessage("선택된 LOG가 존재하지 않습니다.");
    return;
  }
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::LogDeleteButtonClick(TObject* Sender)
{
	int rowIndex = LogReportStringGrid->Row;
	if (rowIndex <= CSVLogList->DataCount)
	{
		if (!LogReportStringGrid->Cells[1][LogReportStringGrid->Row].IsEmpty())
		{
			AnsiString StreamFileName = CSVLogList->GetLogFileName(RowToDataMap[rowIndex]);
			TDateTime SelectedLogTime = CSVLogList->GetTimeInfo(RowToDataMap[rowIndex]);

			if (FileExists(StreamFileName))
			{
				if (MessageDlgFA("삭제된 정보는 복원할 수 없습니다. 계속 진행하시겠습니까?", mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
				{
					StopCSVLogFile();
					bool bRefresh = SearchAndRevisionLogFile(StreamFileName, SelectedLogTime, NULL, 1);
					ResumeCSVLogFile();

					if (bRefresh)
					{
						BrowseButtonClick(BrowseButton);
					}
				}
			}
		}
		else
		{
			ShowMessage("선택된 LOG가 존재하지 않습니다.");
			return;
		}
	}
	else
	{
		ShowMessage("선택된 LOG가 존재하지 않습니다.");
		return;
	}
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::HourEditKeyPress(TObject* Sender,
	char& Key)
{
	Key = NULL;
}
//---------------------------------------------------------------------------

bool __fastcall TAuditTrailForm::SearchAndRevisionLogFile(AnsiString filename, TDateTime SelectedLogTime, TDateTime newLogTime, int mode)
{
  bool returnValue = false;

  AnsiString TimeLabel;
  DateTimeToString(TimeLabel, "yymmdd HH`mm`ss`zzz`", Now());

  AnsiString backupfilename = filename + "_backup_" + TimeLabel;
  CopyFileA(filename.c_str(), backupfilename.c_str(), FALSE);
      
  TFileStream* fileStream = new TFileStream(filename, fmOpenReadWrite);

  bool WriteSW = true;

  if(fileStream)
  {
    Byte *Buffer = new Byte[fileStream->Size];
    fileStream->Read(Buffer, fileStream->Size);
      
    try
    {
      if(mode == 0)
      {
        for(int address = 0; address < fileStream->Size - sizeof(double); address++)
        {
          TDateTime time;
          memcpy(&time.Val, Buffer + address, sizeof(double));

          if(time.Val == SelectedLogTime.Val && time.Val != NULL)
          {
            memcpy(Buffer + address, &newLogTime.Val, sizeof(double));

            returnValue = true;
            break;
          }
        }

        int dateCount = 0;
        for(int address = 0; address < fileStream->Size - sizeof(double); address++)
        {
          TDateTime time;
          memcpy(&time.Val, Buffer + address, sizeof(double));

          if(time.Val == newLogTime.Val && time.Val != NULL)
          {
            dateCount++;
          }
        }

        if(dateCount > 1)
        {
          WriteSW = false;
          ShowMessage("같은 시간의 다른 LOG가 존재하여 변경할 수 없습니다.");
        }
      }
      else if(mode == 1)
      {
        for(int address = 0; address < fileStream->Size - sizeof(double); address++)
        {
          TDateTime time;
          memcpy(&time.Val, Buffer + address, sizeof(double));

          if(time.Val == SelectedLogTime.Val && time.Val != NULL)
          {
            newLogTime.Val = CSV_DELETE_LOG_TIME;
            memcpy(Buffer + address, &newLogTime.Val, sizeof(double));

            returnValue = true;
            break;
          }
        }
      }
    }
    catch(...)
    {

    }

    if(WriteSW)
    {
      fileStream->Position = 0;
      fileStream->Write(Buffer, fileStream->Size);
    }

    if(Buffer) delete Buffer;
    Buffer = NULL;
  }

  delete fileStream;

  return returnValue;
}
//---------------------------------------------------------------------------
void __fastcall TAuditTrailForm::TntButton1Click(TObject *Sender)
{
  AnsiString tmpUserName = eStartUserName->Text;
  WideString tmpProductName = eStartProductName->Text;
  WideString tmpLotName = eLotName->Text;

	TCSVInspectionStartActionLogData csvInspectionStartActionLogData;
	csvInspectionStartActionLogData.IsReInspection = 0;
	csvInspectionStartActionLogData.DesiredInspectionCount = 0;
	csvInspectionStartActionLogData.ReInspectionType = 0;
	csvInspectionStartActionLogData.ReInspectionTabletCount = 0;

	for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
		csvInspectionStartActionLogData.CameraEnabled[globalCameraIndex] = 0;
	}

	csvInspectionStartActionLogData.MachineStopActivated = 0;
	csvInspectionStartActionLogData.MachineStopDefectRatio = 0;
	csvInspectionStartActionLogData.MachineStopUnInsRatio = 0;
	csvInspectionStartActionLogData.NCAsDefect = 0;
	csvInspectionStartActionLogData.MotorSpeed[0] = 0;
	csvInspectionStartActionLogData.MotorSpeed[1] = 0;
	csvInspectionStartActionLogData.MotorSpeed[2] = 0;
	csvInspectionStartActionLogData.MotorSpeed[3] = 0;

  char Temp[64] = {0,};
  WideCharToMultiByte(CP_ACP,0,tmpLotName.c_bstr(),-1,Temp,64,NULL,NULL);
	strncpy(csvInspectionStartActionLogData.LotName, Temp, 64);
  
	AddCSVActionLog(ECSV_ACTION_INSPECTION_START, tmpUserName, tmpProductName, (unsigned char *)&csvInspectionStartActionLogData, sizeof(TCSVInspectionStartActionLogData));

  BrowseButtonClick(BrowseButton);
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::TntButton2Click(TObject *Sender)
{
  AnsiString tmpUserName = eStartUserName->Text;
  WideString tmpProductName = eStartProductName->Text;
  int inspectionCount[4];

	inspectionCount[0] = StrToInt(eTotalCnt->Text);
	inspectionCount[1] = StrToInt(eGoodCnt->Text);
	inspectionCount[2] = StrToInt(eDefectCnt->Text);
	inspectionCount[3] = StrToInt(eUninsCnt->Text);

	AddCSVActionLog(ECSV_ACTION_INSPECTION_PAUSE, tmpUserName, tmpProductName, (unsigned char *)inspectionCount, 4 * sizeof(unsigned int));

  BrowseButtonClick(BrowseButton);
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::TntButton3Click(TObject *Sender)
{
  AnsiString tmpUserName = eStartUserName->Text;
  WideString tmpProductName = eStartProductName->Text;
  WideString tmpLotName = eLotName->Text;

  AddCSVActionLog(ECSV_ACTION_INSPECTION_RESTART, tmpUserName,  tmpProductName, AnsiString(tmpLotName).c_str(),AnsiString(tmpLotName).Length()+1);

  BrowseButtonClick(BrowseButton);  
}
//---------------------------------------------------------------------------


void __fastcall TAuditTrailForm::eStartUserNameClick(TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *) Sender;

	KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeyboard() == mrOk)
  {
		theEdit->Text = KeyboardForm->Text;
  }
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::eTotalCntClick(TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *) Sender;

	KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
  {
    if(StrToInt(KeyboardForm->Text) == 0)
    {
      if(theEdit->Name != "ProductionCountEdit")
      {
        KeyboardForm->Text = "1";
      }
    }

    if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
    {
      theEdit->Text = IntToStr(StrToInt(KeyboardForm->Text));
    }
    else
      theEdit->Text = KeyboardForm->Text;
  }  
}
//---------------------------------------------------------------------------

void __fastcall TAuditTrailForm::ckbShowCSV_OptionClick(TObject *Sender)
{
  if(ckbShowCSV_Option->Checked)
  {
    pnCSV_Option->Visible = true;
  }
  else
  {
    pnCSV_Option->Visible = false;  
  }  
}
//---------------------------------------------------------------------------

