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

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

#include "BackupProcess_Form.h"
#include "Environment.h"
#include "MultiLanguage.h"
#include "Message_Form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CGAUGES"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TBackupProcessForm *BackupProcessForm;
//---------------------------------------------------------------------------
__fastcall TBackupProcessForm::TBackupProcessForm(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
  {
    ComponentSetFontName(this, "Malgun Gothic");
  }
  BreakActivate = false;

  Label1->Caption = BACKUPUTIL_CAPTION_32;
  Label2->Caption = BACKUPUTIL_CAPTION_33;
  Label3->Caption = BACKUPUTIL_CAPTION_34;
  Label4->Caption = BACKUPUTIL_CAPTION_35;
  Label6->Caption = BACKUPUTIL_CAPTION_36;
  Label7->Caption = BACKUPUTIL_CAPTION_37;
  Label5->Caption = BACKUPUTIL_CAPTION_38;
  TntLabel1->Caption = BACKUPUTIL_CAPTION_39;
  BreakButton->Caption = BACKUPUTIL_CAPTION_40;
  this->Caption = BACKUPUTIL_CAPTION_49;

}
//---------------------------------------------------------------------------
int __fastcall TBackupProcessForm::Execute(AnsiString backupDir, TBackupContents backupContents)
{
  try
  {
    BackupDir = backupDir;
    BackupContents = backupContents;
    this->Show();
    BackupStart();
  }
  catch(...)
  {
    	ShowMessageFA(BACKUPUTIL_CAPTION_23);
    return mrCancel;
  }
    ShowMessageFA(BACKUPUTIL_CAPTION_24);
  this->Close();
  return mrOk;
}
//---------------------------------------------------------------------------
void __fastcall TBackupProcessForm::BackupStart(void)
{
  TCursor oldCursor = this->Cursor;
  this->Cursor = crHourGlass;

  CalculateBackupSpaceLabel->Font->Color = clBlue;
  CalculateBackupSpaceLabel->Caption = BACKUPUTIL_CAPTION_20;
  Repaint();
  CalculateBackupSpace();
  CalculateBackupSpaceLabel->Font->Color = clGreen;
  CalculateBackupSpaceLabel->Caption = BACKUPUTIL_CAPTION_21;

  ForceDirectories(BackupDir);
  TIniFile *iniFile = new TIniFile(BackupDir + "\\Information.ini");
  if (iniFile)
  {
    iniFile->WriteDate("Information", "Backup Time", Now());
    delete iniFile;
  }

  if (BackupContents.Contains(bcUserInfo))
  {
    BackupUserInfoLabel->Font->Color = clBlue;
    BackupUserInfoLabel->Caption = BACKUPUTIL_CAPTION_20;
    Repaint();
    BackupUserInfo();
    BackupUserInfoLabel->Font->Color = clGreen;
    BackupUserInfoLabel->Caption = BACKUPUTIL_CAPTION_21;
  }
  else
  {
    BackupUserInfoLabel->Font->Color = clBlue;
    BackupUserInfoLabel->Caption = BACKUPUTIL_CAPTION_22;
  }
  if (BackupContents.Contains(bcSystemInfo))
  {
    BackupSystemInfoLabel->Font->Color = clBlue;
    BackupSystemInfoLabel->Caption = BACKUPUTIL_CAPTION_20;
    Repaint();
    BackupSystemInfo();
    BackupSystemInfoLabel->Font->Color = clGreen;
    BackupSystemInfoLabel->Caption = BACKUPUTIL_CAPTION_21;
  }
  else
  {
    BackupSystemInfoLabel->Font->Color = clBlue;
    BackupSystemInfoLabel->Caption = BACKUPUTIL_CAPTION_22;
  }
  if (BackupContents.Contains(bcProductInfo))
  {
    BackupProductInfoLabel->Font->Color = clBlue;
    BackupProductInfoLabel->Caption = BACKUPUTIL_CAPTION_20;
    ProductBackupProgressGroupBox->Visible = true;
    Repaint();
    BackupProductInfo(BackupContents.Contains(bcProductImage));
    BackupProductInfoLabel->Font->Color = clGreen;
    BackupProductInfoLabel->Caption = BACKUPUTIL_CAPTION_21;
  }
  else
  {
    BackupProductInfoLabel->Font->Color = clBlue;
    BackupProductInfoLabel->Caption = BACKUPUTIL_CAPTION_22;
  }
  if (BackupContents.Contains(bcDefectImage) && !BreakActivate)
  {
    BackupDefectImageLabel->Font->Color = clBlue;
    BackupDefectImageLabel->Caption = BACKUPUTIL_CAPTION_20;
    Repaint();
    BackupDefectImage();
    BackupDefectImageLabel->Font->Color = clGreen;
    BackupDefectImageLabel->Caption = BACKUPUTIL_CAPTION_21;
  }
  else
  {
    BackupDefectImageLabel->Font->Color = clBlue;
    BackupDefectImageLabel->Caption = BACKUPUTIL_CAPTION_22;
  }

    if (BackupContents.Contains(bcAuditTrail) && !BreakActivate)
    {
    	BackupAuditTrailLabel->Font->Color = clBlue;
		BackupAuditTrailLabel->Caption = BACKUPUTIL_CAPTION_20;
		Repaint();
        BackupAuditTrail();
        BackupAuditTrailLabel->Font->Color = clGreen;
	    BackupAuditTrailLabel->Caption = BACKUPUTIL_CAPTION_21;
    }
    else
    {
    	BackupAuditTrailLabel->Font->Color = clBlue;
		BackupAuditTrailLabel->Caption = BACKUPUTIL_CAPTION_22;
	}
  this->Cursor = oldCursor;
}
//---------------------------------------------------------------------------
void __fastcall TBackupProcessForm::CalculateBackupSpace(void)
{

}
//---------------------------------------------------------------------------
bool __fastcall TBackupProcessForm::BackupUserInfo(void)
{
  AnsiString userInfoDir = BackupDir + "\\UserInfo";
  ForceDirectories(userInfoDir);
  AnsiString sourceFileName = ProgramPath.Env + "\\user.ini";
  AnsiString destFileName = userInfoDir + "\\user.ini";
  CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);

  
 sourceFileName = ProgramPath.Env + "\\UserInfor.ini";
    destFileName = userInfoDir + "\\UserInfor.ini";
    CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
    

    
  TIniFile *iniFile = new TIniFile(BackupDir + "\\Information.ini");
  if (iniFile)
  {
    iniFile->WriteBool("Information", "Backup User Info Data", true);
    delete iniFile;
  }
  return true;
}
//---------------------------------------------------------------------------
bool __fastcall TBackupProcessForm::BackupSystemInfo(void)
{
  	AnsiString fileList[17] = {"VersionInfo.ini", "UserMachineInfor.ini", "Ranger3DCameraInfo.ini",
		"MachineInfor.ini", "SystemInfor.ini", "ShutterSpeedInfor.ini", "ColorCode.ini", "Download.ini",
		"DSMInfor.ini", "SystemSetup.ini","DiskLineScanFrequency.ini","Initials.ini","NFACameraInformation.ini",
    "Ranger3DCameraInfo_DiskPos.ini","ThreeDCameraDefaultInfo.ini","UserSetting.ini","WhiteBalanceInfo.ini"};
  AnsiString systemInfoDir = BackupDir + "\\SystemInfo";
  ForceDirectories(systemInfoDir);
  for (int fileIndex = 0; fileIndex < 17; fileIndex++)
  {
    AnsiString sourceFileName = ProgramPath.Env + "\\" + fileList[fileIndex];
    AnsiString destFileName = systemInfoDir + "\\" + fileList[fileIndex];
    CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
  }
  TIniFile *iniFile = new TIniFile(BackupDir + "\\Information.ini");
  if (iniFile)
  {
    iniFile->WriteBool("Information", "Backup System Info Data", true);
    delete iniFile;
  }
  return true;
}
//---------------------------------------------------------------------------
bool __fastcall TBackupProcessForm::BackupProductInfo(bool bIncludeProductImage)
{
  TSearchRec sr;
  int iAttributes = faDirectory;
  AnsiString destDirRoot = BackupDir + "\\Product";
  AnsiString productDir = ProgramPath.Product;

	if(BackupSpeedMode == BACKUP_PROCESS_SPEED_NORMAL) RemoveWholeDir(destDirRoot);
	
	if(!DirectoryExists(destDirRoot))	ForceDirectories(destDirRoot);    

  //    AnsiString srcFile = productDir + "\\*.*";
  //    AnsiString destFile = destDirRoot + "\\*.*";
  //    BOOL bCancel;
  //    CopyFileEx(srcFile.c_str(), destFile.c_str(), NULL, NULL, &bCancel, 0);

  int productCount = 0;
  if (FindFirst(productDir + "\\*.*", iAttributes, sr) == 0)
  {
    do
    {
      if ((sr.Attr & iAttributes) == sr.Attr && sr.Name != "." && sr.Name != "..")
      {
        productCount++;
      }
    } while (FindNext(sr) == 0);
    FindClose(sr);
  }

  int currentProductCount = 0;

  if (FindFirst(productDir + "\\*.*", iAttributes, sr) == 0)
  {
    do
    {
      if ((sr.Attr & iAttributes) == sr.Attr && sr.Name != "." && sr.Name != "..")
      {
        ProductNameLabel->Caption = sr.Name;
        if (productCount)
        {
          CGauge1->Progress = currentProductCount * 100 / productCount;
        }
        if (bIncludeProductImage)
        {
          CopyDir(destDirRoot + "\\" + sr.Name, productDir + "\\" + sr.Name);
        }
        else
        {
          CopyDirExcludeImage(destDirRoot + "\\" + sr.Name, productDir + "\\" + sr.Name);
        }
        currentProductCount++;
      }
    } while (FindNext(sr) == 0);
    FindClose(sr);
  }
  if (!BreakActivate)
  {
    TIniFile *iniFile = new TIniFile(BackupDir + "\\Information.ini");
    if (iniFile)
    {
      iniFile->WriteBool("Information", "Backup Product Info Data", true);
      delete iniFile;
    }
  }
  return true;
}
//---------------------------------------------------------------------------
bool __fastcall TBackupProcessForm::BackupDefectImage(void)
{
  	TSearchRec sr;
    int iAttributes = faDirectory;
	AnsiString destDirRoot = BackupDir + "\\Defect";
    AnsiString productDir = ProgramPath.Defect;

	if(BackupSpeedMode == BACKUP_PROCESS_SPEED_NORMAL) RemoveWholeDir(destDirRoot);
	
	if(!DirectoryExists(destDirRoot))	ForceDirectories(destDirRoot);    


	int productCount = 0;
	if (FindFirst(productDir + "\\*.*", iAttributes, sr) == 0)
	{
		do
		{
			if ((sr.Attr & iAttributes) == sr.Attr && sr.Name != "." && sr.Name != "..")
			{
				productCount++;
			}
		} while (FindNext(sr) == 0);
		FindClose(sr);
	}

	int currentProductCount = 0;

	if (FindFirst(productDir + "\\*.*", iAttributes, sr) == 0)
	{
		do
		{
			if ((sr.Attr & iAttributes) == sr.Attr && sr.Name != "." && sr.Name != "..")
			{
				ProductNameLabel->Caption = sr.Name;

					CopyDir(destDirRoot + "\\" + sr.Name, productDir + "\\" + sr.Name);
				currentProductCount++;
			}
		} while (FindNext(sr) == 0);
		FindClose(sr);
	}

    TIniFile *iniFile = new TIniFile(BackupDir + "\\Information.ini");
    if (iniFile)
    {
        iniFile->WriteBool("Information", "Backup Defect Image Data", true);
        delete iniFile;
    }
    return true;
}
//---------------------------------------------------------------------------
bool __fastcall TBackupProcessForm::BackupAuditTrail(void)
{
    AnsiString tempStr, srcPath, dirPath;
    int idx, logCnt , iAttributes, result;
	TSearchRec sr;
	bool unReadFileExist, failToWrite;

    dirPath = BackupDir + "\\CSV Log\\";

	if(BackupSpeedMode == BACKUP_PROCESS_SPEED_NORMAL) RemoveWholeDir(dirPath);
	
	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);

            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;
            }
            delete fileStreamRead;
        } while (FindNext(sr) == 0);
        FindClose(sr);
    }
    if(failToWrite)
        return false;
    else
    {            
        TIniFile *iniFile = new TIniFile(BackupDir + "\\Information.ini");
        if (iniFile)
        {
            iniFile->WriteBool("Information", "Backup Audit Trail Data", true);
            delete iniFile;
        }
    }
        
    return true;
}
//---------------------------------------------------------------------------
void __fastcall TBackupProcessForm::CopyDir(AnsiString destDir, AnsiString srcDir)
{
  TSearchRec sr;
  int iAttributes = faAnyFile;
  CreateDir(destDir);
  if (FindFirst(srcDir + "\\*.*", iAttributes, sr) == 0)
  {
    do
    {
      if (sr.Name == "." || sr.Name == "..") continue;
      if ((sr.Attr & faDirectory))
      {
        CopyDir(destDir + "\\" + sr.Name, srcDir + "\\" + sr.Name);
      }
      else
      {
        AnsiString sourceFileName = srcDir + "\\" + sr.Name;
        AnsiString destFileName = destDir + "\\" + sr.Name;
        CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
      }
      Application->ProcessMessages();
      if (BreakActivate) break;
    } while (FindNext(sr) == 0);
    FindClose(sr);
  }
}
//---------------------------------------------------------------------------
void __fastcall TBackupProcessForm::CopyDirExcludeImage(AnsiString destDir, AnsiString srcDir)
{
  TSearchRec sr;
  int iAttributes = faAnyFile;
  CreateDir(destDir);
  if (FindFirst(srcDir + "\\*.*", iAttributes, sr) == 0)
  {
    do
    {
      if (sr.Name == "." || sr.Name == "..") continue;
      if ((sr.Attr & faDirectory))
      {
        if (sr.Name == "Image")
        {
          CreateDir(destDir + "\\Image");
          CopyOneImage(destDir + "\\Image", srcDir + "\\Image");
        }
        else
        {
          CopyDir(destDir + "\\" + sr.Name, srcDir + "\\" + sr.Name);
        }
      }
      else
      {
        AnsiString sourceFileName = srcDir + "\\" + sr.Name;
        AnsiString destFileName = destDir + "\\" + sr.Name;
        CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
      }
      Application->ProcessMessages();
      if (BreakActivate) break;
    } while (FindNext(sr) == 0);
    FindClose(sr);
  }
}
//---------------------------------------------------------------------------
void __fastcall TBackupProcessForm::CopyOneImage(AnsiString destDir, AnsiString srcDir)
{
  AnsiString sourceFileName, destFileName;
  for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    sourceFileName = srcDir + "\\Image1_" + IntToStr(globalCameraIndex + 1) + ".bmp";
    destFileName = destDir + "\\Image1_" + IntToStr(globalCameraIndex + 1) + ".bmp";
    CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
  }
  sourceFileName = srcDir + "\\Image1_1_O.bmp";
  destFileName = destDir + "\\Image1_1_O.bmp";
  CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
  sourceFileName = srcDir + "\\Image1_6_O.bmp";
  destFileName = destDir + "\\Image1_6_O.bmp";
  CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
}
//---------------------------------------------------------------------------
void __fastcall TBackupProcessForm::BreakButtonClick(TObject *Sender)
{
  BreakActivate = true;
}
//---------------------------------------------------------------------------
void __fastcall TBackupProcessForm::RemoveWholeDir(AnsiString folderName)
{
	TSearchRec sr;
	int iAttributes = faAnyFile;
	if (FindFirst(folderName + "\\*.*", iAttributes, sr) == 0)
	{
		do
		{
			if (sr.Name == "." || sr.Name == "..") continue;
			if (sr.Attr & faDirectory)
			{
				RemoveWholeDir(folderName + "\\" + sr.Name);
			}
			else
			{
				//                if (MessageDlgFA(folderName + "\\" + sr.Name + " 을 정말 삭제하겠습니까?", mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
				{
					DeleteFile(folderName + "\\" + sr.Name);
				}
			}

		} while (FindNext(sr) == 0);
		FindClose(sr);
		//        if (MessageDlgFA(folderName + " 을 정말 삭제하겠습니까?", mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
		{
			RemoveDir(folderName);
		}
	}
}

