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

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

#include "Main_Form.h"
#include "Environment.h"                                                                                                                                                                                              
//#include "ProductList_Form.h"                                                                                                                                                                             
#include "ProductInput_Form.h"
#include "SetPath_Form.h"                                                                                                                                                            
#include "TabletSimulation_Form.h"
#include "Message_Form.h"
//#include "GradeSetting_Form.h"                                                                                                                                                                                                 
#include "GradeSetting.h"
#include "First_Study.h"                                                                                                                                                                     
//#include "Calibration_Form.h"                                                                                                                                                                     
#include "CPBTuning_Form.h"
#include "TabletCharacterExtract.h"                                                                                                                                                                                                                          
#include "CPB_Module_Main.h"                                                                
#include "SecStudy_Form.h"

//---------------------------------------------------------------------------                                                                                                                   
#pragma package(smart_init)                                                                                                   
#pragma link "TntButtons"
#pragma link "TntStdCtrls"                                                                                                                       
#pragma resource "*.dfm"                                                                                                                                                                        
TMainForm *MainForm;

TMESProductData MESProductData;

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

__fastcall TMainForm::TMainForm(TComponent* Owner)
	: TTntForm(Owner)
{
}                                                                                                          
//---------------------------------------------------------------------------

void __fastcall TMainForm::Button1Click(TObject *Sender)
{
	TProductInputForm *productInputForm = new TProductInputForm(this);

	if (productInputForm->ShowModal() == mrOk)
	{
		AnsiString gradeFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".grd";

		if (!LoadGradeData(gradeFileName, TabletGradeData))
		{                                                                             
			ShowMessageFA("등급 정보가 존재하지 않아 초기값을 적용합니다.");
			SetDefaultGradeData(TabletGradeData);
			SaveGradeData(gradeFileName, TabletGradeData);
		}                                                                                                 
                                                                                     
		ClearInspectionData();                                                                         
		RefreshProductInfo();

    TIniFile *iniFile = new TIniFile(ProgramPath.Env + "Virtual.ini");
    if (iniFile)
    {
      iniFile->WriteString("Recent", "Product Code", ProductData.ProductCode);
      iniFile->WriteString("Recent", "LOT", ProductData.LOTName);
      delete iniFile;
    }
	}                                                                                                                                        
	delete productInputForm;                                                             
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FormCreate(TObject *Sender)
{
    AnsiString RootPath;
    AnsiString DebugFileName;
    bool bExistDebugFile;

	UserInfo.AccessLevel = SYSTEM_HIGHEST_ACCESS_LEVEL;

	if (!SetProgramPath(ProgramPath))
	{
		SetPathForm = new TSetPathForm(this);
		if (SetPathForm->ShowModal() == mrOk)
		{
			SetProgramPath(ProgramPath);
		}
		delete SetPathForm;
	}

  RootPath = ExtractFileDir(Application->ExeName);
  DebugFileName = RootPath + "\\swdebug.ini";
  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]");
      }
    }
    else
    {
      GlobalProgramID = PROGRAM_ID_200; // 0 : 200, 1 : 150p, 2 : 200
    }

  if(GlobalProgramID == PROGRAM_ID_150P)
  {
    MachineTypeComboBox->ItemIndex = 0;
  }
  else
  {
    MachineTypeComboBox->ItemIndex = 1;
  }

    
	Environment_Init();

	// load recent product data
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "Virtual.ini");
	if (iniFile)
	{
		AnsiString recentProductCode = iniFile->ReadString("Recent", "Product Code", "");
		AnsiString recentLOT = iniFile->ReadString("Recent", "LOT", "");

		AnsiString productFileName = GetProductDataFileName(recentProductCode);
		if (ReadProductData(productFileName, ProductData, MachineParams, MachineSetupData))
		{
			ProductData.LOTName = recentLOT;

			AnsiString gradeFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".grd";
			if (!LoadGradeData(gradeFileName, TabletGradeData))
			{
				ShowMessageFA("등급 정보가 존재하지 않아 초기값을 적용합니다.");
				SetDefaultGradeData(TabletGradeData);
				SaveGradeData(gradeFileName, TabletGradeData);
			}

			RefreshProductInfo();
		}

		delete iniFile;
	}

}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RefreshProductInfo(void)
{
	ProductNameLabel->Caption = ProductData.ProductName;
	LOTNameLabel->Caption = ProductData.LOTName;
	switch (ProductData.TabletType)
	{
	case TABLET_TYPE_UNKNOWN:
		TabletTypeLabel->Caption = "?";
		break;
	case TABLET_TYPE_UNCOATED:
		TabletTypeLabel->Caption = "나정";
		break;
	case TABLET_TYPE_FILM_COATED:
		TabletTypeLabel->Caption = "필름코팅정";
		break;
	case TABLET_TYPE_SUGAR_COATED:
		TabletTypeLabel->Caption = "당의정";
		break;
	case TABLET_TYPE_OTHER:
		TabletTypeLabel->Caption = "기타";
		break;
	}
	switch (ProductData.TabletShape)
	{
	case TABLET_SHAPE_UNKNOWN:
		TabletShapeLabel->Caption = "?";
		break;
	case TABLET_SHAPE_CIRCLE:
		TabletShapeLabel->Caption = "Circle";
		break;
	case TABLET_SHAPE_OBLONG:
		TabletShapeLabel->Caption = "Oblong";
		break;
	case TABLET_SHAPE_OVAL:
		TabletShapeLabel->Caption = "Oval";
		break;
	case TABLET_SHAPE_ETC:
		TabletShapeLabel->Caption = "Etc";
		break;
	}
	TabletLengthLabel->Caption = FloatToStr(ProductData.TabletLength) + "mm";
	TabletWidthLabel->Caption = FloatToStr(ProductData.TabletWidth) + "mm";
	TabletThickLabel->Caption = FloatToStr(ProductData.TabletThick) + "mm";
	TabletSideThickLabel->Caption = FloatToStr(ProductData.TabletSideThick) + "mm";
	switch (ProductData.EngraveType)
	{
	case ENGRAVE_TYPE_UNKNOWN:
		EngraveTypeLabel->Caption = "?";
		break;
	case ENGRAVE_TYPE_RELIEF:
		EngraveTypeLabel->Caption = "양각";
		break;
	case ENGRAVE_TYPE_INTAGLIO:
		EngraveTypeLabel->Caption = "음각";
		break;
	case ENGRAVE_TYPE_PRINT:
		EngraveTypeLabel->Caption = "인쇄";
		break;
	case ENGRAVE_TYPE_EMPTY:
		EngraveTypeLabel->Caption = "없음";
		break;
	}
	switch (ProductData.EngravePos)
	{
	case ENGRAVE_POS_UNKNOWN:
		EngravePosLabel->Caption = "?";
		break;
	case ENGRAVE_POS_ONESIDE:
		EngravePosLabel->Caption = "한쪽";
		break;
	case ENGRAVE_POS_SAME:
		EngravePosLabel->Caption = "양쪽동일";
		break;
	case ENGRAVE_POS_DIFF:
		EngravePosLabel->Caption = "양쪽";
		break;
	}

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

void __fastcall TMainForm::InspectionButtonClick(TObject *Sender)
{
	AnsiString gradeFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".grd";
	if (!LoadGradeData(gradeFileName, TabletGradeData))
	{
		ShowMessageFA("등급 정보가 존재하지 않아 초기값을 적용합니다.");
		SetDefaultGradeData(TabletGradeData);
		SaveGradeData(gradeFileName, TabletGradeData);
	}
	TabletSimulationForm->Show();
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FormDestroy(TObject *Sender)
{
	// save recent product data                                                                           
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "Virtual.ini");
	if (iniFile)
	{
		iniFile->WriteString("Recent", "Product Code", ProductData.ProductCode);
		iniFile->WriteString("Recent", "LOT", ProductData.LOTName);
		delete iniFile;
	}
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::GradeSettingButtonClick(TObject *Sender)
{
	TGradeSettingForm *gradeSettingForm = new TGradeSettingForm(this);
	gradeSettingForm->SetGradeData(&TabletGradeData_PC);
	gradeSettingForm->bUserMakingGradeData = false;
	if (gradeSettingForm->ShowModal() == mrOk)
	{
		gradeSettingForm->GetGradeData(&TabletGradeData_PC);
		AnsiString gradeFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".grd";
		SaveGradeData(gradeFileName, TabletGradeData_PC);
	}
	delete gradeSettingForm;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FirstStudyButtonClick(TObject *Sender)
{
	TFirstStudy *FirstStudy = new TFirstStudy(this);
	FirstStudy->ShowModal();
	delete FirstStudy;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::UserGradeSpeedButtonClick(TObject *Sender)
{
	TTntSpeedButton *theSpeedButton = (TTntSpeedButton *)Sender;
	UserInfo.AccessLevel = SYSTEM_HIGHEST_ACCESS_LEVEL;
}
//---------------------------------------------------------------------------  
void __fastcall TMainForm::CPBTuningButtonClick(TObject *Sender)
{
	TCPBTuningForm *cpbTuningForm = new TCPBTuningForm(this);                                   
	cpbTuningForm->ShowModal();
	delete cpbTuningForm;
}                                                                                                           
//---------------------------------------------------------------------------

void __fastcall TMainForm::TabletCharacterExtractButtonClick(
	TObject *Sender)
{
	TTabletCharacterExtractForm *tabletCharacterExtractForm = new TTabletCharacterExtractForm(this);
  tabletCharacterExtractForm->SetupMode = TABLET_SETUP_MODE_NORMAL;
	tabletCharacterExtractForm->ShowModal();
	delete tabletCharacterExtractForm;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::SecStudyBtnClick(TObject *Sender)
{
	TSecondStudyFom *SecondStudyForm = new TSecondStudyFom(this);
	SecondStudyForm->ShowModal();
	delete SecondStudyForm;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::SetLastSafetyMode(int newSafeMode)
{
	return;
}

void __fastcall TMainForm::MachineTypeComboBoxChange(TObject *Sender)
{
    AnsiString RootPath;
    int CrruentGlobalProgramID = GlobalProgramID;
    AnsiString DebugFileName;
    bool bExistDebugFile;

  if(((MachineTypeComboBox->ItemIndex)+1) == PROGRAM_ID_200)
  {
    GlobalProgramID = PROGRAM_ID_200;
  }
  else
  {
    GlobalProgramID = PROGRAM_ID_150P;
  }    

      if(CrruentGlobalProgramID != GlobalProgramID)
      {
        RootPath = ExtractFileDir(Application->ExeName);
        DebugFileName = RootPath + "\\swdebug.ini";

        TIniFile *iniFile = new TIniFile(DebugFileName);
        iniFile->WriteInteger("Debugging", "Program ID", GlobalProgramID); // 0 : 200, 1 : 150p, 2 : 200
        delete iniFile;

        ShowMessageW("Machine Type 이 변경되었습니다 프로그램이 종료됩니다");
        //FormDestroy
        Application->Terminate();
      }
 
  DisconnectCSVLogFile();
  
	Environment_Init();

	// load recent product data
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "Virtual.ini");
	if (iniFile)
	{
		AnsiString recentProductCode = iniFile->ReadString("Recent", "Product Code", "");
		AnsiString recentLOT = iniFile->ReadString("Recent", "LOT", "");

		AnsiString productFileName = GetProductDataFileName(recentProductCode);
		if (ReadProductData(productFileName, ProductData, MachineParams, MachineSetupData))
		{
			ProductData.LOTName = recentLOT;

			AnsiString gradeFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".grd";
			if (!LoadGradeData(gradeFileName, TabletGradeData))
			{
				ShowMessageFA("등급 정보가 존재하지 않아 초기값을 적용합니다.");
				SetDefaultGradeData(TabletGradeData);
				SaveGradeData(gradeFileName, TabletGradeData);
			}

			RefreshProductInfo();
		}

		delete iniFile;
	}  
}
//---------------------------------------------------------------------------

