//---------------------------------------------------------------------------
// For SELMA200, 20180223, moon, 변경사항 없음
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "IntervalSetting_Form.h"
#include "MultiLanguage.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntExtCtrls"
#pragma link "TntGrids"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TIntervalSettingForm *IntervalSettingForm;
//---------------------------------------------------------------------------
__fastcall TIntervalSettingForm::TIntervalSettingForm(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);
  }

  memset(TabletList, 0, PC_TABLET_LIST_COUNT * sizeof(TPCTabletUnit));
  RefreshStringGrid();
}
//---------------------------------------------------------------------------
void __fastcall TIntervalSettingForm::RefreshStringGrid(void)
{
    IntervalStringGrid->Cells[0][0] = "Num.";
    IntervalStringGrid->Cells[1][0] = "State";
    IntervalStringGrid->Cells[2][0] = "S1 Time";
	IntervalStringGrid->Cells[3][0] = "S2 Time";
	IntervalStringGrid->Cells[4][0] = "S3 Time";
	IntervalStringGrid->Cells[5][0] = "Interval A";
	IntervalStringGrid->Cells[6][0] = "Interval B";
	IntervalStringGrid->Cells[7][0] = "A Diff.";
	IntervalStringGrid->Cells[8][0] = "B Diff.";
	IntervalStringGrid->Cells[9][0] = "Num.";
	IntervalStringGrid->Cells[10][0] = "State";
	IntervalStringGrid->Cells[11][0] = "S1 Time";
	IntervalStringGrid->Cells[12][0] = "S2 Time";
	IntervalStringGrid->Cells[13][0] = "S3 Time";
	IntervalStringGrid->Cells[14][0] = "Interval A";
	IntervalStringGrid->Cells[15][0] = "Interval B";
	IntervalStringGrid->Cells[16][0] = "A Diff.";
	IntervalStringGrid->Cells[17][0] = "B Diff.";

    for (int tabletTableIndex = 0; tabletTableIndex < PC_TABLET_LIST_COUNT; tabletTableIndex++)
    {
        TPCTabletUnit *pcTabletUnit = &TabletList[tabletTableIndex];
        TTntStringGrid *statusStringGrid = IntervalStringGrid;

		statusStringGrid->Cells[0 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = IntToStr(pcTabletUnit->TabletNumber);

		switch (pcTabletUnit->HCBState)
		{
			case TABLET_STATE_READY:
				statusStringGrid->Cells[1 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = "Ready";
				break;
			case TABLET_STATE_SENSOR_1_PASSED:
				statusStringGrid->Cells[1 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = "S1 Passed";
				break;
			case TABLET_STATE_SENSOR_2_PASSED:
				statusStringGrid->Cells[1 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = "S2 Passed";
				break;
			case TABLET_STATE_COMPLETE:
                statusStringGrid->Cells[1 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = "Complete";
                break;
        }
		statusStringGrid->Cells[2 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = IntToStr(pcTabletUnit->Sensor1Time);
		statusStringGrid->Cells[3 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = IntToStr(pcTabletUnit->Sensor2Time);
		statusStringGrid->Cells[4 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = IntToStr(pcTabletUnit->Sensor3Time);
		statusStringGrid->Cells[5 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = IntToStr(pcTabletUnit->Sensor2Time - pcTabletUnit->Sensor1Time);
		statusStringGrid->Cells[6 + (tabletTableIndex % 2 * 9)][tabletTableIndex / 2 + 1] = IntToStr(pcTabletUnit->Sensor3Time - pcTabletUnit->Sensor2Time);

    }

    StartButton->Caption		= INTERVALSETTINGFORM_BUTTON_CAPTION_01;
    StopButton->Caption 		= INTERVALSETTINGFORM_BUTTON_CAPTION_02;
    CalculateButton->Caption 	= INTERVALSETTINGFORM_BUTTON_CAPTION_03;
    SetupButton->Caption 		= INTERVALSETTINGFORM_BUTTON_CAPTION_04;

    GroupBox1->Caption 		= INTERVALSETTINGFORM_GROUPBOX_CAPTION_01;
    GroupBox2->Caption 		= INTERVALSETTINGFORM_GROUPBOX_CAPTION_02;

    Label1->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_01;
    Label2->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_02;
    Label4->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_03;

    Label6->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_01;
    Label8->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_02;
    Label10->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_03;

    TntLabel1->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_04;
    TntLabel2->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_05;
    Label5->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_06;
    Label7->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_07;

    Label3->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_08;
    TntLabel3->Caption 		= INTERVALSETTINGFORM_LABEL_CAPTION_09;

}
//---------------------------------------------------------------------------

void __fastcall TIntervalSettingForm::StartButtonClick(TObject *Sender)
{
//	int func = 1;
	struct
	{
		int func;
		float TabletLength;
		int SuctionDiskSpeed;
		int StudiedTabletSensorLength;
	} checkIntervalSetupData;
	checkIntervalSetupData.func = 1;
	checkIntervalSetupData.TabletLength = ProductData.TabletLength;
	checkIntervalSetupData.SuctionDiskSpeed = MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed;
	checkIntervalSetupData.StudiedTabletSensorLength = ProductData.TabletLength / MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_1 * 20.0 * 1000;

	if (!Comm_Request(COMM_HCB, CMD_CHECK_SENSOR_INTERVAL, &checkIntervalSetupData, sizeof(checkIntervalSetupData)))
	{
		//ShowMessageW(HCBConnection.GetLastErrorMessage());
	}
	StatusReadTimer->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TIntervalSettingForm::StopButtonClick(TObject *Sender)
{
	int func = 0;
	if (!Comm_Request(COMM_HCB, CMD_CHECK_SENSOR_INTERVAL, &func, sizeof(int)))
	{
		//ShowMessageW(HCBConnection.GetLastErrorMessage());
    }

    StatusReadTimer->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TIntervalSettingForm::StatusReadTimerTimer(TObject *Sender)
{
    int requestNum = 1;
	TTabletInfo TabletInfo;
	if (!Comm_Request(COMM_HCB, CMD_TABLET_PROCESS_INFO, &requestNum, sizeof(int),
		&TabletInfo, sizeof(TTabletInfo)))
	{
		StatusReadTimer->Enabled = false;
		//ShowMessageW(HCBConnection.GetLastErrorMessage());
    }

    IntervalData.CurrentSensor1ListIndex = TabletInfo.CurrentSensor1ListIndex;
    IntervalData.CurrentSensor2ListIndex = TabletInfo.CurrentSensor2ListIndex;

    for (int tabletTableIndex = 0; tabletTableIndex < HCB_TABLET_LIST_COUNT; tabletTableIndex++)
	{
		THCBDisk1TabletUnit *hcbDisk1TabletUnit = &TabletInfo.Disk1TabletList[tabletTableIndex];
		THCBDisk2TabletUnit *hcbDisk2TabletUnit = &TabletInfo.Disk2TabletList[tabletTableIndex];
		THCBCounterTabletUnit *hcbCounterTabletUnit = &TabletInfo.CounterTabletList[tabletTableIndex];
		TPCTabletUnit *pcTabletUnit = &TabletList[tabletTableIndex];

		pcTabletUnit->TabletNumber = hcbDisk2TabletUnit->TabletNumber;
		pcTabletUnit->InspectionResult = hcbDisk2TabletUnit->InspectionResult;
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
			pcTabletUnit->InspectionResult_SPB[spbIndex] = hcbDisk2TabletUnit->InspectionResult_SPB[spbIndex];
        }
		pcTabletUnit->HCBState = hcbDisk2TabletUnit->State;
		pcTabletUnit->Sensor1Time = hcbDisk1TabletUnit->Sensor1Time;
		pcTabletUnit->EstimatedSensor2Time = hcbDisk2TabletUnit->EstimatedSensor2Time;
		pcTabletUnit->Sensor2Time = hcbDisk2TabletUnit->Sensor2Time;
		pcTabletUnit->Sensor3Time = hcbCounterTabletUnit->Sensor3Time;
        for (int captureIndex = 0; captureIndex < SYSTEM_MACHINE_CAPTURE_COUNT; captureIndex++)
        {
			pcTabletUnit->IsLEDOn[captureIndex] = hcbDisk2TabletUnit->IsLEDOn[captureIndex];
        }
    }

    RefreshStringGrid();
}
//---------------------------------------------------------------------------

void __fastcall TIntervalSettingForm::CalculateButtonClick(TObject *Sender)
{
	int intervalASum = 0;
	int intervalACount = 0;
	int minIntervalA = 0;
	int maxIntervalA = 0;

	int intervalBSum = 0;
	int intervalBCount = 0;
	int minIntervalB = 0;
	int maxIntervalB = 0;

  int intervalRatio = StrToInt(VDSpeedEdit->Text);

  int CalcIntervalA, CalcIntervalB;

	for (int tabletTableIndex = 0; tabletTableIndex < HCB_TABLET_LIST_COUNT; tabletTableIndex++)
	{
		TPCTabletUnit *pcTabletUnit = &TabletList[tabletTableIndex];

		if (pcTabletUnit->HCBState == TABLET_STATE_COMPLETE)
		{
			int intervalAValue = pcTabletUnit->Sensor2Time - pcTabletUnit->Sensor1Time;


      if(intervalAValue > 0 && intervalAValue < 50000) // 50000 -> 임의로 Interval의 Max값을 50000으로 가정
      {        
        intervalASum += intervalAValue;

        if (intervalACount == 0)
        {
          minIntervalA = intervalAValue;
          maxIntervalA = intervalAValue;
        }
        else
        {
          if (minIntervalA > intervalAValue)
          {
            minIntervalA = intervalAValue;
          }
          if (maxIntervalA < intervalAValue)
          {
            maxIntervalA = intervalAValue;
          }
        }
        intervalACount++;
      }

      int intervalBValue = pcTabletUnit->Sensor3Time - pcTabletUnit->Sensor2Time;

      if(intervalBValue > 0 && intervalAValue < 50000) // 50000 -> 임의로 Interval의 Max값을 50000으로 가정
      {        
        intervalBSum += intervalBValue;

        if (intervalBCount == 0)
        {
          minIntervalB = intervalBValue;
          maxIntervalB = intervalBValue;
        }
        else
        {
          if (minIntervalB > intervalBValue)
          {
            minIntervalB = intervalBValue;
          }
          if (maxIntervalB < intervalBValue)
          {
            maxIntervalB = intervalBValue;
          }
        }
        intervalBCount++;
      }
		}
	}
  
	if (intervalACount > 0)
	{
		AverageIntervalA = intervalASum / intervalACount;
	}
	else
	{
		AverageIntervalA = 0;
	}

	if (intervalBCount > 0)
	{
		AverageIntervalB = intervalBSum / intervalBCount;
	}
	else
	{
		AverageIntervalB = 0;
	}

  if (intervalACount > 0)
  {
    AverageIntervalALabel->Caption = IntToStr(AverageIntervalA);
    MinIntervalALabel->Caption = IntToStr(minIntervalA);
    MaxIntervalALabel->Caption = IntToStr(maxIntervalA);
    CalcIntervalA = AverageIntervalA * intervalRatio / 100;
    CalcSetupValueAEdit->Text = IntToStr(CalcIntervalA);
  }
  else
  {
    AverageIntervalALabel->Caption = IntToStr(0);
    MinIntervalALabel->Caption = IntToStr(0);
    MaxIntervalALabel->Caption = IntToStr(0);
    CalcIntervalA = 0;
    CalcSetupValueAEdit->Text = IntToStr(CalcIntervalA);
  }

  if (intervalBCount > 0)
  {
    AverageIntervalBLabel->Caption = IntToStr(AverageIntervalB);
    MinIntervalBLabel->Caption = IntToStr(minIntervalB);
    MaxIntervalBLabel->Caption = IntToStr(maxIntervalB);
    CalcIntervalB = AverageIntervalB * intervalRatio / 100;
    CalcSetupValueBEdit->Text = IntToStr(CalcIntervalB);
  }
  else
  {
    AverageIntervalBLabel->Caption = IntToStr(0);
    MinIntervalBLabel->Caption = IntToStr(0);
    MaxIntervalBLabel->Caption = IntToStr(0);
    CalcIntervalB = 0;
    CalcSetupValueBEdit->Text = IntToStr(CalcIntervalB);
  }
}
//---------------------------------------------------------------------------
void __fastcall TIntervalSettingForm::SetupButtonClick(TObject *Sender)
{
	int intervalA;
	int intervalB;

  if(StrToInt(CalcSetupValueAEdit->Text) != 0 && StrToInt(CalcSetupValueBEdit->Text) != 0)
  {
    intervalA = StrToInt(CalcSetupValueAEdit->Text);
    intervalB = StrToInt(CalcSetupValueBEdit->Text);
  }
  else
  {
    ShowMessage("Please calculate intervalA, B");
    return;
  }

	MachineSetupData.SensorIntervalA = intervalA;
	MachineSetupData.SensorIntervalB = intervalB;

  SetupValueAEdit->Text = IntToStr(MachineSetupData.SensorIntervalA);
  SetupValueBEdit->Text = IntToStr(MachineSetupData.SensorIntervalB);

  WriteMachineSetupData(ProgramPath.Env + "\\SystemInfor.ini", MachineSetupData);

  ShowMessage("System Information Setup!");

	if (!Comm_Request(COMM_HCB, CMD_MACHINE_PARAM_SETUP, &MachineSetupData, sizeof(TMachineSetupData)))
	{
		//ShowMessageW(HCBConnection.GetLastErrorMessage());
	}
	else
	{
		ShowMessageW(INTERVALSETTINGFORM_MSG_01);
	}
}
//---------------------------------------------------------------------------
void __fastcall TIntervalSettingForm::TntFormCreate(TObject *Sender)
{
  CalcSetupValueAEdit->Text = IntToStr(0);
  CalcSetupValueBEdit->Text = IntToStr(0);

  VDSpeedEdit->Text = IntToStr(MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed * 100 / MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX]);
	SetupValueAEdit->Text = IntToStr(MachineSetupData.SensorIntervalA);
	SetupValueBEdit->Text = IntToStr(MachineSetupData.SensorIntervalB);
}
//---------------------------------------------------------------------------

