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

#include <vcl.h>
#include <math.h>
#include <inifiles.hpp>
#pragma hdrstop

#include "NCControl_Form.h"
#include "Environment.h"
#include "Message_Form.h"
#include "MultiLanguage.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntExtCtrls"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TNCControlForm *NCControlForm;
//---------------------------------------------------------------------------
__fastcall TNCControlForm::TNCControlForm(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();

	SelectedControlIndex = -1;
	NCPosParamMul[0] = NC_POS_PARAM_1_MUL;
	NCPosParamMul[1] = NC_POS_PARAM_2_MUL;
	NCPosParamMul[2] = NC_POS_PARAM_3_MUL;
	NCPosParamMul[3] = NC_POS_PARAM_4_MUL;
	NCPosParamMul[4] = NC_POS_PARAM_5_MUL;

	NCPosParamDiv[0] = NC_POS_PARAM_1_DIV;
	NCPosParamDiv[1] = NC_POS_PARAM_2_DIV;
	NCPosParamDiv[2] = NC_POS_PARAM_3_DIV;
	NCPosParamDiv[3] = NC_POS_PARAM_4_DIV;
	NCPosParamDiv[4] = NC_POS_PARAM_5_DIV;

	UserMinusLimitPortIndex[0] = IP_NC_1_LIMIT_L;
	UserPlusLimitPortIndex[0] = IP_NC_1_LIMIT_H;
	UserMinusLimitPortIndex[1] = IP_NC_2_LIMIT_L;
	UserPlusLimitPortIndex[1] = IP_NC_2_LIMIT_H;
	UserMinusLimitPortIndex[2] = IP_NC_3_LIMIT_H;
	UserPlusLimitPortIndex[2] = IP_NC_3_LIMIT_L;
	UserMinusLimitPortIndex[3] = IP_NC_4_LIMIT_H;
	UserPlusLimitPortIndex[3] = IP_NC_4_LIMIT_L;
	UserMinusLimitPortIndex[4] = IP_NC_5_LIMIT_L;
	UserPlusLimitPortIndex[4] = IP_NC_5_LIMIT_H;
	int EncoderMinusLimitPortIndex[MAX_STEP_MOTOR_COUNT];
	int EncoderPlusLimitPortIndex[MAX_STEP_MOTOR_COUNT];
	FIsMEMode = false;
	FNCOriginDetected = false;
	//this->Width = 1473;
	//this->Height = 1063;
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::GetDefaultString()
{
  CloseButton->Caption = NCCONTROLFORM_BUTTON_CAPTION_01;
  SaveProductDataButton->Caption = NCCONTROLFORM_BUTTON_CAPTION_02;
  this->Caption = NCCONTROLFORM_FORM_CAPTION_01;
  NCControlGroupBox->Caption = NCCONTROLFORM_GROUPBOX_CAPTION_01;
  Label15->Caption = NCCONTROLFORM_LABEL_CAPTION_01;
  Label11->Caption = NCCONTROLFORM_LABEL_CAPTION_02;
  Label13->Caption = NCCONTROLFORM_LABEL_CAPTION_03;
  NCInterlockAPanel->Caption = NCCONTROLFORM_LABEL_CAPTION_04;
  Label9->Caption = NCCONTROLFORM_LABEL_CAPTION_05;
  Label1->Caption = NCCONTROLFORM_LABEL_CAPTION_06;
  ImagePanel->Caption = NCCONTROLFORM_PANEL_CAPTION_01;
  OriginWarningPanel->Caption = NCCONTROLFORM_PANEL_CAPTION_02;

  StepMotorMinusLimitPanel3->Caption 	= "- " + NCCONTROLFORM_LABEL_CAPTION_07;
  StepMotorPlusLimitPanel3->Caption 	= "+ " + NCCONTROLFORM_LABEL_CAPTION_07;

  StepMotorMinusLimitPanel4->Caption 	= "- " + NCCONTROLFORM_LABEL_CAPTION_07;
  StepMotorPlusLimitPanel4->Caption 	= "+ " + NCCONTROLFORM_LABEL_CAPTION_07;

  StepMotorMinusLimitPanel1->Caption 	= "- " + NCCONTROLFORM_LABEL_CAPTION_07;
  StepMotorPlusLimitPanel1->Caption 	= "+ " + NCCONTROLFORM_LABEL_CAPTION_07;

  StepMotorMinusLimitPanel5->Caption 	= "- " + NCCONTROLFORM_LABEL_CAPTION_07;
  StepMotorPlusLimitPanel5->Caption 	= "+ " + NCCONTROLFORM_LABEL_CAPTION_07;

  StepMotorMinusLimitPanel2->Caption 	= "- " + NCCONTROLFORM_LABEL_CAPTION_07;
  StepMotorPlusLimitPanel2->Caption 	= "+ " + NCCONTROLFORM_LABEL_CAPTION_07;

  
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::ControlPanelClick(TObject *Sender)
{
	if (FIsMEMode) return;

	TControl *theControl = (TControl *) Sender;
	for (int panelIndex = 0; panelIndex < 5; panelIndex++)
	{
		TTntPanel *aPanel = (TTntPanel *)FindComponent("ControlPanel" + IntToStr(panelIndex + 1));
		if (aPanel)
		{
			aPanel->Color = clBlack;
		}
	}
	if (SelectedControlIndex != theControl->Tag)
	{
		SelectedControlIndex = theControl->Tag;
		TTntPanel *aPanel = (TTntPanel *)FindComponent("ControlPanel" + IntToStr(SelectedControlIndex + 1));
		if (aPanel)
		{
			aPanel->Color = clBlue;
		}
		NCControlGroupBox->Visible = true;
		InstructionImage->Visible = true;

    AnsiString imageFileName;
		if(DefaultLCID == 1042 || DefaultLCID == 2066)
    {
      imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
    }
    else if(DefaultLCID == 1033)
    {
        if(SelectedControlIndex != 1)
            imageFileName = ProgramPath.Env +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        else
            imageFileName = ProgramPath.Env + "\\En" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
    }
    else if(DefaultLCID == 1041)
    {
      if(SelectedControlIndex != 1)
            imageFileName = ProgramPath.Env +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        else
            imageFileName = ProgramPath.Env + "\\Jp" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
    }
    else if(DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
    {
      if(SelectedControlIndex != 1)
            imageFileName = ProgramPath.Env +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        else
            imageFileName = ProgramPath.Env + "\\Ch" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
    }
    else if(DefaultLCID == 1028)
    {
      if(SelectedControlIndex != 1)
            imageFileName = ProgramPath.Env +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        else
            imageFileName = ProgramPath.Env + "\\Tiw" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
    }
    else if(DefaultLCID == 3082)
    {
        if(SelectedControlIndex != 1)
            imageFileName = ProgramPath.Env +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        else
            imageFileName = ProgramPath.Env + "\\Sp" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
    }

		if (FileExists(imageFileName))
		{
			InstructionImage->Picture->LoadFromFile(imageFileName);
		}
		//this->ClientWidth = MenuPanel->Width + 1000;
	}
	else
	{
		SelectedControlIndex = -1;
		NCControlGroupBox->Visible = false;
		InstructionImage->Visible = false;
		//this->ClientWidth = MenuPanel->Width;
	}
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::CloseButtonClick(TObject *Sender)
{
	this->Close();
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::Timer1Timer(TObject *Sender)
{
	Machine.ReadMachineStatus();
	Machine.ReadPortStatus();

  WCHAR TempString[100];
  wsprintfW(TempString, L"%Smm", FloatToStrF( Machine.Status.StepMotorAbsEncoder[0] * (double)NCPosParamDiv[0] / NCPosParamMul[0] - MachineSetupData.ZeroPositionValue[0], ffFixed, 10, 2));
  NCPosLabel1->Caption = TempString;
  wsprintfW(TempString, L"%Smm", FloatToStrF( Machine.Status.StepMotorAbsEncoder[1] * (double)NCPosParamDiv[1] / NCPosParamMul[1] - MachineSetupData.ZeroPositionValue[1], ffFixed, 10, 2));
  NCPosLabel2->Caption = TempString;
  wsprintfW(TempString, L"%Smm", FloatToStrF( Machine.Status.StepMotorAbsEncoder[2] * (double)NCPosParamDiv[2] / NCPosParamMul[2] - MachineSetupData.ZeroPositionValue[2], ffFixed, 10, 2));
  NCPosLabel3->Caption = TempString;
  wsprintfW(TempString, L"%Smm", FloatToStrF( Machine.Status.StepMotorAbsEncoder[3] * (double)NCPosParamDiv[3] / NCPosParamMul[3] - MachineSetupData.ZeroPositionValue[3], ffFixed, 10, 2));
  NCPosLabel4->Caption = TempString;



  double suctionDisk2Position = Machine.Status.StepMotorAbsEncoder[4] * (double)NCPosParamDiv[4] / NCPosParamMul[4] - MachineSetupData.ZeroPositionValue[4];
	double suctionDiskDistance = sqrt((SUCTION_DISK_DISTANCE_BASE_X + suctionDisk2Position) * (SUCTION_DISK_DISTANCE_BASE_X + suctionDisk2Position) + SUCTION_DISK_DISTANCE_Y * SUCTION_DISK_DISTANCE_Y) - SUCTION_DISK_DIAMETER;


  wsprintfW(TempString, L"%Smm [D = %Smm]", FloatToStrF(suctionDisk2Position, ffFixed, 10, 2),  FloatToStrF( suctionDiskDistance, ffFixed, 10, 2));
//  wsprintfW(TempString, L"%.2fmm [D = %.Smm]", suctionDisk2Position, FloatToStrF( suctionDiskDistance, ffFixed, 10, 2));

  NCPosLabel5->Caption = TempString;

	if (SelectedControlIndex != -1)
	{
		CurrentNCValue = (Machine.Status.StepMotorAbsEncoder[SelectedControlIndex] * (double)NCPosParamDiv[SelectedControlIndex] / NCPosParamMul[SelectedControlIndex] - MachineSetupData.ZeroPositionValue[SelectedControlIndex] + 0.005) * 100;
		int currentNCAbsValue = abs(CurrentNCValue);
		CurrentNCValueDigit[0] = currentNCAbsValue / 1000 % 10;
		CurrentNCValueDigit[1] = currentNCAbsValue / 100 % 10;
		CurrentNCValueDigit[2] = currentNCAbsValue / 10 % 10;
		CurrentNCValueDigit[3] = currentNCAbsValue / 1 % 10;

		if (CurrentNCValue > 0)
		{
			NCValueLabel1->Caption = IntToStr(CurrentNCValueDigit[0]);
		}
		else
		{
			NCValueLabel1->Caption = "-";
		}
		NCValueLabel2->Caption = IntToStr(CurrentNCValueDigit[1]);
		NCValueLabel3->Caption = IntToStr(CurrentNCValueDigit[2]);
		NCValueLabel4->Caption = IntToStr(CurrentNCValueDigit[3]);
	}

	if (Machine.Status.MEStatus.Connected && Machine.Status.MEStatus.Enabled)
	{
		FIsMEMode = true;
		HMEGroupBox->Visible = true;
		NCControlGroupBox->Visible = false;
	}
	if (FIsMEMode)
	{
		for (int panelIndex = 0; panelIndex < 5; panelIndex++)
		{
			TTntPanel *aPanel = (TTntPanel *)FindComponent("ControlPanel" + IntToStr(panelIndex + 1));
			if (aPanel)
			{
				aPanel->Color = clBlack;
			}
		}

		if (SelectedControlIndex != Machine.Status.MEStatus.MotorIndex)
		{
			SelectedControlIndex = Machine.Status.MEStatus.MotorIndex;

			if (SelectedControlIndex != -1)
			{
        AnsiString imageFileName;
        if(DefaultLCID == 1042 || DefaultLCID == 2066)
        {
          imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        }
        else if(DefaultLCID == 1033)
        {
          imageFileName = ProgramPath.Env + "\\En" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        }
        else if(DefaultLCID == 1041)
        {
          imageFileName = ProgramPath.Env + "\\Jp" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        }
        else if(DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
        {
          imageFileName = ProgramPath.Env + "\\Ch" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        }
        else if(DefaultLCID == 1028)
        {
          imageFileName = ProgramPath.Env + "\\Tiw" +"\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
        }

				if (FileExists(imageFileName))
				{
					InstructionImage->Picture->LoadFromFile(imageFileName);
				}
			}
		}


		if (SelectedControlIndex != -1)
		{
			TTntPanel *aPanel = (TTntPanel *)FindComponent("ControlPanel" + IntToStr(SelectedControlIndex + 1));
			if (aPanel)
			{
				aPanel->Color = clBlue;
			}
			InstructionImage->Visible = true;
		}
		else
		{
			InstructionImage->Visible = false;
		}
	}

	for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
	{
		TTntPanel *minusLimitPanel = (TTntPanel *) FindComponent("StepMotorMinusLimitPanel" + IntToStr(stepMotorIndex + 1));
		if (minusLimitPanel)
		{
			if (Machine.PortStatus.IPStatus[UserMinusLimitPortIndex[stepMotorIndex]])
			{
				minusLimitPanel->Color = clRed;
			}
			else
			{
				minusLimitPanel->Color = clBlack;
			}
		}
		TTntPanel *plusLimitPanel = (TTntPanel *) FindComponent("StepMotorPlusLimitPanel" + IntToStr(stepMotorIndex + 1));
		if (plusLimitPanel)
		{
			if (Machine.PortStatus.IPStatus[UserPlusLimitPortIndex[stepMotorIndex]])
			{
				plusLimitPanel->Color = clRed;
			}
			else
			{
				plusLimitPanel->Color = clBlack;
			}
		}
	}

//	if ((Machine.Status.StepMotorAbsEncoder[VG2_UP_DOWN_MOTOR_INDEX] * 100 / NC_POS_PARAM_4 -
//		Machine.Status.StepMotorAbsEncoder[BF_UP_DOWN_MOTOR_INDEX] * 100 / NC_POS_PARAM_1)
	if ((Machine.Status.StepMotorAbsEncoder[VG2_UP_DOWN_MOTOR_INDEX] * 100 * NC_POS_PARAM_4_DIV / NC_POS_PARAM_4_MUL -
		Machine.Status.StepMotorAbsEncoder[BF_UP_DOWN_MOTOR_INDEX] * 100 * NC_POS_PARAM_1_DIV / NC_POS_PARAM_1_MUL)
		>= MachineSetupData.InterlockInfo.NCInterlockAValue - 1)
	{
		NCInterlockAPanel->Color = clRed;
	}
	else
	{
		NCInterlockAPanel->Color = clBlack;
	}

	bool originDetected = true;
	for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
	{
		if (!Machine.Status.OriginDetected[stepMotorIndex])
		{
			originDetected = false;
			break;
		}
	}
	FNCOriginDetected = originDetected;
	if (!FNCOriginDetected)
	{
		OriginWarningPanel->Visible = true;
	}
	else
	{
		OriginWarningPanel->Visible = false;
	}

  // 2015-10-20 revision by moon 대기상테에서만 위치정보를 저장할 수 있도록 함
  // 2015-11-18 revision by moon 장비가 클리닝 상태나 대기, 클리닝중인 상태가 아니라면 머신 상태를 저장할 수 있도록 수정
  if(Machine.Status.OperationState != MACHINE_STATE_CLEANING &&
    Machine.Status.OperationState != MACHINE_STATE_DETACHING &&
    Machine.Status.OperationState != MACHINE_STATE_ATTACHING)
    SaveProductDataButton->Enabled = true;
  else
    SaveProductDataButton->Enabled = false;
  //--------------------------------------------------------------------------

	if (Machine.Status.OperationState == MACHINE_STATE_STOP ||
		Machine.Status.OperationState == MACHINE_STATE_CLEANING)
	{
		NCControlUpButton1->Visible = true;
		NCControlDownButton1->Visible = true;
	}
	else
	{
		NCControlUpButton1->Visible = false;
		NCControlDownButton1->Visible = false;
	}
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::NCControlUpButtonClick(TObject *Sender)
{
	if (SelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *) Sender;
	int divVal = pow(10, theButton->Tag);

	Machine.NCMovePos(SelectedControlIndex, CurrentNCValue / 100.0 + 1.0 / divVal);
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::NCControlDownButtonClick(TObject *Sender)
{
	if (SelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *) Sender;
	int divVal = pow(10, theButton->Tag);

	Machine.NCMovePos(SelectedControlIndex, CurrentNCValue / 100.0 - 1.0 / divVal);
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::SaveProductDataButtonClick(TObject *Sender)
{
	if (MessageDlgFA(NCCONTROLFORM_MSG_01, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
	{
    for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
    {
      //ProductData.NCMotorPos[stepMotorIndex] = (Machine.Status.StepMotorAbsEncoder[stepMotorIndex] - MachineSetupData.ZeroEncoderValue[stepMotorIndex]) / (double)NCPosParam[stepMotorIndex];
      ProductData.NCMotorPos[stepMotorIndex] = ((double)Machine.Status.StepMotorAbsEncoder[stepMotorIndex] * 1000.0 * (double)NCPosParamDiv[stepMotorIndex] / (double)NCPosParamMul[stepMotorIndex] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[stepMotorIndex];
    }

		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			machineSettingChangeData.NewNCPos[stepMotorIndex] = ProductData.NCMotorPos[stepMotorIndex];
		}

		AddCSVActionLog(ECSV_ACTION_CHANGE_MACHINE_SETTING, UserInfo.Name, ProductData.ProductName, (unsigned char *)&machineSettingChangeData, sizeof(TCSVMachineSettingChangeData));

    AnsiString fileName = GetProductDataFileName(ProductData.ProductCode);
    if (ProductDataModified())
    {
      BackupProductData(EPDBR_MACHINE_SETTING_CHANGE);
    }
    WriteProductData(fileName, ProductData);
	}
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::FormActivate(TObject *Sender)
{
	memset(&machineSettingChangeData, 0, sizeof(TCSVMachineSettingChangeData));

	for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
	{
		machineSettingChangeData.OldNCPos[stepMotorIndex] = ProductData.NCMotorPos[stepMotorIndex];
	}		
    
	if (FIsMEMode)
	{
		HMEGroupBox->Visible = true;
		NCControlGroupBox->Visible = false;
	}
	else
	{
		HMEGroupBox->Visible = false;
		NCControlGroupBox->Visible = true;
	}
	Timer1->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TNCControlForm::FormDeactivate(TObject *Sender)
{
	Timer1->Enabled = false;
}
//---------------------------------------------------------------------------


