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

#include <vcl.h>
#pragma hdrstop

#include "RestoreProcess_Form.h"
#include "Message_Form.h"
#include "MultiLanguage.h"
#include "Environment.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CGAUGES"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TRestoreProcessForm *RestoreProcessForm;
//---------------------------------------------------------------------------
__fastcall TRestoreProcessForm::TRestoreProcessForm(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_41;
  Label3->Caption = BACKUPUTIL_CAPTION_42;
  Label4->Caption = BACKUPUTIL_CAPTION_43;
  Label6->Caption = BACKUPUTIL_CAPTION_36;
  Label7->Caption = BACKUPUTIL_CAPTION_37;
  Label5->Caption = BACKUPUTIL_CAPTION_44;
  TntLabel1->Caption = BACKUPUTIL_CAPTION_45;
  BreakButton->Caption = BACKUPUTIL_CAPTION_40;
  this->Caption = BACKUPUTIL_CAPTION_50;  
}
//---------------------------------------------------------------------------
int __fastcall TRestoreProcessForm::Execute(AnsiString backupDir, TBackupContents backupContents)
{
	try
    {
    	BackupDir = backupDir;
    	BackupContents = backupContents;
		this->Show();
        RestoreStart();
    }
    catch(...)
    {
		ShowMessageFA(BACKUPUTIL_CAPTION_18);
		this->Close();
		return mrCancel;
    }
    ShowMessageFA(BACKUPUTIL_CAPTION_19);
    this->Close();
	return mrOk;
}
//---------------------------------------------------------------------------
void __fastcall TRestoreProcessForm::RestoreStart(void)
{
	CalculateRestoreSpaceLabel->Font->Color = clBlue;
	CalculateRestoreSpaceLabel->Caption = BACKUPUTIL_CAPTION_20;
	Repaint();
	CalculateRestoreSpace();
	CalculateRestoreSpaceLabel->Font->Color = clGreen;
	CalculateRestoreSpaceLabel->Caption = BACKUPUTIL_CAPTION_21;


	if (BackupContents.Contains(bcUserInfo))
	{
		RestoreUserInfoLabel->Font->Color = clBlue;
		RestoreUserInfoLabel->Caption = BACKUPUTIL_CAPTION_20;
		Repaint();
		RestoreUserInfo();
		RestoreUserInfoLabel->Font->Color = clGreen;
		RestoreUserInfoLabel->Caption = BACKUPUTIL_CAPTION_21;
	}
	else
	{
		RestoreUserInfoLabel->Font->Color = clBlue;
		RestoreUserInfoLabel->Caption = BACKUPUTIL_CAPTION_22;
	}
	if (BackupContents.Contains(bcSystemInfo))
	{
		RestoreSystemInfoLabel->Font->Color = clBlue;
		RestoreSystemInfoLabel->Caption = BACKUPUTIL_CAPTION_20;
		Repaint();
		RestoreSystemInfo();
		RestoreSystemInfoLabel->Font->Color = clGreen;
		RestoreSystemInfoLabel->Caption = BACKUPUTIL_CAPTION_21;
	}
	else
	{
		RestoreSystemInfoLabel->Font->Color = clBlue;
		RestoreSystemInfoLabel->Caption = BACKUPUTIL_CAPTION_22;
	}
	if (BackupContents.Contains(bcProductInfo))
	{
		RestoreProductInfoLabel->Font->Color = clBlue;
		RestoreProductInfoLabel->Caption = BACKUPUTIL_CAPTION_20;
		ProductBackupProgressGroupBox->Visible = true;
		Repaint();
		RestoreProductInfo();
		if (BreakActivate) throw Exception("");
		RestoreProductInfoLabel->Font->Color = clGreen;
		RestoreProductInfoLabel->Caption = BACKUPUTIL_CAPTION_21;
	}
	else
	{
		RestoreProductInfoLabel->Font->Color = clBlue;
		RestoreProductInfoLabel->Caption = BACKUPUTIL_CAPTION_22;
	}
	if (BackupContents.Contains(bcDefectImage))
	{
		RestoreDefectImageLabel->Font->Color = clBlue;
		RestoreDefectImageLabel->Caption = BACKUPUTIL_CAPTION_20;
		Repaint();
		RestoreDefectImage();
		RestoreDefectImageLabel->Font->Color = clGreen;
		RestoreDefectImageLabel->Caption = BACKUPUTIL_CAPTION_21;
	}
	else
	{
		RestoreDefectImageLabel->Font->Color = clBlue;
		RestoreDefectImageLabel->Caption = BACKUPUTIL_CAPTION_22;
	}
    if (BackupContents.Contains(bcAuditTrail))
	{
		RestoreAuditTrailLabel->Font->Color = clBlue;
		RestoreDefectImageLabel->Caption = BACKUPUTIL_CAPTION_20;
		Repaint();
		RestoreAuditTrail();
		RestoreAuditTrailLabel->Font->Color = clGreen;
		RestoreAuditTrailLabel->Caption = BACKUPUTIL_CAPTION_21;
	}
	else
	{
		RestoreAuditTrailLabel->Font->Color = clBlue;
		RestoreAuditTrailLabel->Caption = BACKUPUTIL_CAPTION_22;
	}
}
//---------------------------------------------------------------------------
void __fastcall TRestoreProcessForm::CalculateRestoreSpace(void)
{

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

  sourceFileName = userInfoDir + "\\UserInfor.ini";
	destFileName = ProgramPath.Env + "\\UserInfor.ini";
	CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
	return true;
}
//---------------------------------------------------------------------------
bool __fastcall TRestoreProcessForm::RestoreSystemInfo(void)
{
	if (!DirectoryExists(ProgramPath.Env)) ForceDirectories(ProgramPath.Env);

		AnsiString fileList[19] = {"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","LSFStudyResultTable.lsf","SystemAuthorityInformation.ini"};
	AnsiString systemInfoDir = BackupDir + "\\SystemInfo";
	for (int fileIndex = 0; fileIndex < 19; fileIndex++)
	{
		AnsiString sourceFileName = systemInfoDir + "\\" + fileList[fileIndex];
		AnsiString destFileName = ProgramPath.Env + "\\" + fileList[fileIndex];
		CopyFileA(sourceFileName.c_str(), destFileName.c_str(), FALSE);
	}
    return true;    
}
//---------------------------------------------------------------------------
bool __fastcall TRestoreProcessForm::RestoreProductInfo(void)
{
	if (!DirectoryExists(ProgramPath.Product)) ForceDirectories(ProgramPath.Product);

	TSearchRec sr;
    int iAttributes = faDirectory;
	AnsiString sourceDirRoot = BackupDir + "\\Product";
	AnsiString productDir = ProgramPath.Product;

	int productCount = 0;

	if(BackupSpeedMode == BACKUP_PROCESS_SPEED_NORMAL) RemoveWholeDir(productDir);
	
    if(!DirectoryExists(productDir)) ForceDirectories(productDir);    	
	
	if (FindFirst(sourceDirRoot + "\\*.*", 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(sourceDirRoot + "\\*.*", 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;
				}
				CopyDir(productDir + "\\" + sr.Name, sourceDirRoot + "\\" + sr.Name);
				currentProductCount++;
			}
        } while (FindNext(sr) == 0);
        FindClose(sr);
    }
    return true;
}
//---------------------------------------------------------------------------
bool __fastcall TRestoreProcessForm::RestoreDefectImage(void)
{
 if (!DirectoryExists(ProgramPath.Defect)) ForceDirectories(ProgramPath.Defect);

	TSearchRec sr;
    int iAttributes = faDirectory;
	AnsiString sourceDirRoot = BackupDir + "\\Defect";
	AnsiString productDir = ProgramPath.Defect;

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

	int productCount = 0;
	if (FindFirst(sourceDirRoot + "\\*.*", 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(sourceDirRoot + "\\*.*", 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;
				}
				CopyDir(productDir + "\\" + sr.Name, sourceDirRoot + "\\" + sr.Name);
				currentProductCount++;
			}
        } while (FindNext(sr) == 0);
        FindClose(sr);
    }
    return true;
}
bool __fastcall TRestoreProcessForm::RestoreAuditTrail(void)
{  
    AnsiString tempStr, srcPath, dirPath;
    int idx, logCnt , iAttributes, result;
	TSearchRec sr;
	bool unReadFileExist, failToWrite;

    srcPath = BackupDir + "\\CSV Log\\";
    dirPath = ProgramPath.Log + "\\CSV Log";

	if(BackupSpeedMode == BACKUP_PROCESS_SPEED_NORMAL) RemoveWholeDir(dirPath);

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


    iAttributes  = faAnyFile;
    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
    {   
    }
        
    return true;
}
//---------------------------------------------------------------------------
void __fastcall TRestoreProcessForm::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 TRestoreProcessForm::BreakButtonClick(TObject *Sender)
{
	BreakActivate = true;	
}
//---------------------------------------------------------------------------
void __fastcall TRestoreProcessForm::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);
		}
	}
}
