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

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

#include "Main_Form.h"
#include "BackupProcess_Form.h"
#include "RestoreProcess_Form.h"
#include "Environment.h"
#include "Message_Form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TMainForm *MainForm;
//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
	: TTntForm(Owner)
{
	
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::DriveComboBoxChange(TObject *Sender)
{
	__int64 freeSpace = DiskFree(DriveComboBox->Drive - 'a' + 1);
    int freeSpaceSize = freeSpace / 1024 / 1024;
	FreeDiscSpaceLabel->Caption = FloatToStrF(freeSpaceSize / 1024.0, ffFixed, 5, 2) + " GB";
    BackupInfoSpeedButton->Down = true;
    BackupInfoSpeedButton->Click();
    RefreshBackupList();
	RefreshRestoreStringGrid();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FormCreate(TObject *Sender)
{
	if (!SetProgramPath(ProgramPath))
    {
		ShowMessageFA("ELMA-100 설치 경로를 찾을 수 없습니다.");
        BackupSpeedButton->Enabled = false;
		RestoreSpeedButton->Enabled = false;
        Application->Terminate();
    }

    Command = BC_INFO;
	BackupDataInfoPanel->BringToFront();
    RefreshBackupList();
    CalculateDataSize();
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::BackupInfoSpeedButtonClick(TObject *Sender)
{
    Command = BC_INFO;
	BackupDataInfoPanel->BringToFront();
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::BackupSpeedButtonClick(TObject *Sender)
{
	Command = BC_BACKUP;
	BackupPanel->BringToFront();
	RefreshBackupPanel();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RestoreSpeedButtonClick(TObject *Sender)
{
	Command = BC_RESTORE;
	RefreshRestoreStringGrid();
	RestorePanel->BringToFront();
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::BackupStartButtonClick(TObject *Sender)
{
	TBackupContents backupContents;
    if (BCUserInfoCheckBox->Checked)
    {
		backupContents = backupContents << bcUserInfo;
    }
    if (BCSystemInfoCheckBox->Checked)
    {
		backupContents = backupContents << bcSystemInfo;
	}
	if (BCProductInfoCheckBox->Checked)
	{
		backupContents = backupContents << bcProductInfo;
		if (IncludeTabletImageCheckBox->Checked)
		{
			backupContents = backupContents << bcProductImage;
		}
	}
    if (BCDefectImageCheckBox->Checked)
    {
		backupContents = backupContents << bcDefectImage;
    }

	AnsiString backupDir = AnsiString(DriveComboBox->Drive) + ":\\ELMA-100 Backups\\" + Now().DateString();
	TBackupProcessForm *backupProcessForm = new TBackupProcessForm(this);
	if (backupProcessForm->Execute(backupDir, backupContents) == mrOk)
	{
		BackupInfoSpeedButton->Down = true;
		BackupInfoSpeedButton->Click();
		RefreshBackupList();
	}
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RefreshBackupList(void)
{
	int iAttributes = faDirectory;
	AnsiString backupDir = AnsiString(DriveComboBox->Drive) + ":\\ELMA-100 Backups";

    BackupInfoList.clear();
    TSearchRec sr;
    if (DirectoryExists(backupDir))
    {
        if (FindFirst(backupDir + "\\*.*", iAttributes, sr) == 0)
        {
        	do
            {
            	if ((sr.Attr & iAttributes) == sr.Attr && sr.Name != "." && sr.Name != "..")
                {
                    TBackupInfoUnit backupInfoUnit;

                    TIniFile *iniFile = new TIniFile(backupDir + "\\" + sr.Name + "\\Information.ini");
                    if (iniFile)
                    {
                        backupInfoUnit.Dir = backupDir + "\\" + sr.Name;
                        backupInfoUnit.BackupTime = iniFile->ReadDate("Information", "Backup Time", 0);
                        backupInfoUnit.UserInfoExist = iniFile->ReadBool("Information", "Backup User Info Data", false);
                        backupInfoUnit.SystemInfoExist = iniFile->ReadBool("Information", "Backup System Info Data", false);
                        backupInfoUnit.ProductInfoExist = iniFile->ReadBool("Information", "Backup Product Info Data", false);
                        backupInfoUnit.DefectImageExist = iniFile->ReadBool("Information", "Backup Defect Image Data", false);
                        BackupInfoList.push_back(backupInfoUnit);
                        delete iniFile;
                    }
                }
            } while (FindNext(sr) == 0);
            FindClose(sr);
        }
    }
    RefreshStringGrid();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RefreshStringGrid(void)
{
    if (BackupInfoList.size() > 0)
    {
        BackupInfoStringGrid->RowCount = BackupInfoList.size() + 1;
    }
    else
    {
        BackupInfoStringGrid->RowCount = 2;
        BackupInfoStringGrid->Cells[0][1] = "";
        BackupInfoStringGrid->Cells[1][1] = "";
        BackupInfoStringGrid->Cells[2][1] = "";
        BackupInfoStringGrid->Cells[3][1] = "";
        BackupInfoStringGrid->Cells[4][1] = "";
    }
    BackupInfoStringGrid->ColWidths[0] = 300;
    BackupInfoStringGrid->Cells[0][0] = "백업 날짜";
    BackupInfoStringGrid->Cells[1][0] = "작업자 정보";
    BackupInfoStringGrid->Cells[2][0] = "시스템 정보";
    BackupInfoStringGrid->Cells[3][0] = "정제 정보";
    BackupInfoStringGrid->Cells[4][0] = "불량 이미지";

    vector<TBackupInfoUnit>::iterator it;
    int rowIndex = 1;
    for (it = BackupInfoList.begin(); it < BackupInfoList.end(); it++)
    {
        if (it->BackupTime.Val == 0)
        {
            BackupInfoStringGrid->Cells[0][rowIndex] = "알 수 없음";
        }
        else
        {
            BackupInfoStringGrid->Cells[0][rowIndex] = it->BackupTime.DateString();
        }
        if (it->UserInfoExist)
        {
            BackupInfoStringGrid->Cells[1][rowIndex] = "O";
        }
        else
        {
            BackupInfoStringGrid->Cells[1][rowIndex] = "X";
        }
        if (it->SystemInfoExist)
        {
            BackupInfoStringGrid->Cells[2][rowIndex] = "O";
        }
        else
        {
            BackupInfoStringGrid->Cells[2][rowIndex] = "X";
        }
        if (it->ProductInfoExist)
        {
            BackupInfoStringGrid->Cells[3][rowIndex] = "O";
        }
        else
        {
            BackupInfoStringGrid->Cells[3][rowIndex] = "X";
        }
        if (it->DefectImageExist)
        {
            BackupInfoStringGrid->Cells[4][rowIndex] = "O";
        }
        else
        {
            BackupInfoStringGrid->Cells[4][rowIndex] = "X";
        }
        rowIndex++;
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RefreshRestoreStringGrid(void)
{
    if (BackupInfoList.size() > 0)
    {
        RestoreStringGrid->RowCount = BackupInfoList.size() + 1;
    }
    else
    {
        RestoreStringGrid->RowCount = 2;
        RestoreStringGrid->Cells[0][1] = "";
        RestoreStringGrid->Cells[1][1] = "";
        RestoreStringGrid->Cells[2][1] = "";
        RestoreStringGrid->Cells[3][1] = "";
        RestoreStringGrid->Cells[4][1] = "";
    }
    RestoreStringGrid->ColWidths[0] = 300;
    RestoreStringGrid->Cells[0][0] = "백업 날짜";
    RestoreStringGrid->Cells[1][0] = "작업자 정보";
    RestoreStringGrid->Cells[2][0] = "시스템 정보";
    RestoreStringGrid->Cells[3][0] = "정제 정보";
    RestoreStringGrid->Cells[4][0] = "불량 이미지";

    vector<TBackupInfoUnit>::iterator it;
    int rowIndex = 1;
    for (it = BackupInfoList.begin(); it < BackupInfoList.end(); it++)
    {
        if (it->BackupTime.Val == 0)
        {
            RestoreStringGrid->Cells[0][rowIndex] = "알 수 없음";
        }
        else
        {
            RestoreStringGrid->Cells[0][rowIndex] = it->BackupTime.DateString();
        }
        if (it->UserInfoExist)
        {
            RestoreStringGrid->Cells[1][rowIndex] = "O";
        }
        else
        {
            RestoreStringGrid->Cells[1][rowIndex] = "X";
        }
        if (it->SystemInfoExist)
        {
            RestoreStringGrid->Cells[2][rowIndex] = "O";
        }
        else
        {
            RestoreStringGrid->Cells[2][rowIndex] = "X";
        }
        if (it->ProductInfoExist)
        {
            RestoreStringGrid->Cells[3][rowIndex] = "O";
        }
        else
        {
            RestoreStringGrid->Cells[3][rowIndex] = "X";
        }
        if (it->DefectImageExist)
        {
            RestoreStringGrid->Cells[4][rowIndex] = "O";
        }
        else
        {
            RestoreStringGrid->Cells[4][rowIndex] = "X";
        }
        rowIndex++;
    }
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::RestoreButtonClick(TObject *Sender)
{
	TBackupContents backupContents;
    int listIndex = RestoreStringGrid->Row - 1;
    if (RCUserInfoCheckBox->Checked && BackupInfoList[listIndex].UserInfoExist)
    {
		backupContents = backupContents << bcUserInfo;
    }
    if (RCSystemInfoCheckBox->Checked && BackupInfoList[listIndex].SystemInfoExist)
    {
		backupContents = backupContents << bcSystemInfo;
    }
    if (RCProductInfoCheckBox->Checked && BackupInfoList[listIndex].ProductInfoExist)
    {
		backupContents = backupContents << bcProductInfo;
    }
    if (RCDefectImageCheckBox->Checked && BackupInfoList[listIndex].DefectImageExist)
    {
		backupContents = backupContents << bcDefectImage;
    }

	AnsiString backupDir = BackupInfoList[RestoreStringGrid->Row - 1].Dir;
	TRestoreProcessForm *restoreProcessForm = new TRestoreProcessForm(this);
	if (restoreProcessForm->Execute(backupDir, backupContents) == mrOk)
    {
        //
    }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::RestoreStringGridSelectCell(TObject *Sender,
      int ACol, int ARow, bool &CanSelect)
{
    int listIndex = ARow - 1;
    if (listIndex < 0 || listIndex >= BackupInfoList.size()) return;
    if (BackupInfoList[listIndex].UserInfoExist)
    {
        RCUserInfoCheckBox->Enabled = true;
    }
    else
    {
        RCUserInfoCheckBox->Enabled = false;
    }
    if (BackupInfoList[listIndex].SystemInfoExist)
    {
        RCSystemInfoCheckBox->Enabled = true;
    }
    else
    {
        RCSystemInfoCheckBox->Enabled = false;
    }
    if (BackupInfoList[listIndex].ProductInfoExist)
    {
        RCProductInfoCheckBox->Enabled = true;
    }
	else
    {
        RCProductInfoCheckBox->Enabled = false;
    }
    if (BackupInfoList[listIndex].DefectImageExist)
    {
        RCDefectImageCheckBox->Enabled = true;
    }
    else
    {
        RCDefectImageCheckBox->Enabled = false;
    }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ExitButtonClick(TObject *Sender)
{
    Application->Terminate();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::CalculateDataSize(void)
{
	__int64 userInfoDataSize = CalculateUserInfoDataSize();
    UserInfoDataSizeLabel->Caption = "(용량: " + GetDataSizeStr(userInfoDataSize) + ")";
	__int64 systemInfoDataSize = CalculateSystemInfoDataSize();
    SystemInfoDataSizeLabel->Caption = "(용량: " + GetDataSizeStr(systemInfoDataSize) + ")";
	__int64 productInfoDataSize = CalculateProductInfoDataSize();
    ProductInfoDataSizeLabel->Caption = "(용량: 최대 " + GetDataSizeStr(productInfoDataSize) + ")";

}
//---------------------------------------------------------------------------
__int64 __fastcall TMainForm::CalculateUserInfoDataSize(void)
{
	__int64 dataSize = 0;
    AnsiString sourceFileName = ProgramPath.Env + "\\user.ini";
    if (FileExists(sourceFileName))
    {
	    TFileStream *fileStream = new TFileStream(sourceFileName, fmOpenRead);
	    if (fileStream)
	    {
	    	dataSize += fileStream->Size;
			delete fileStream;
	    }
    }
	return dataSize;
}
//---------------------------------------------------------------------------
__int64 __fastcall TMainForm::CalculateSystemInfoDataSize(void)
{
	AnsiString fileList[5] = {"MachineInfor.ini", "SystemInfor.ini", "ShutterSpeedInfor.ini", "ColorCode.ini", "Download.ini"};
	__int64 dataSize = 0;
    for (int fileIndex = 0; fileIndex < 5; fileIndex++)
    {
	    AnsiString sourceFileName = ProgramPath.Env + "\\" + fileList[fileIndex];
	    if (FileExists(sourceFileName))
	    {
		    TFileStream *fileStream = new TFileStream(sourceFileName, fmOpenRead);
		    if (fileStream)
		    {
		    	dataSize += fileStream->Size;
				delete fileStream;
		    }
	    }
    }
	return dataSize;
}
//---------------------------------------------------------------------------
__int64 __fastcall TMainForm::CalculateProductInfoDataSize(void)
{
	__int64 dataSize = 0;
	TSearchRec sr;
    int iAttributes = faDirectory;
    AnsiString productDir = ProgramPath.Product;
    if (FindFirst(productDir + "\\*.*", iAttributes, sr) == 0)
    {
    	do
        {
        	if ((sr.Attr & iAttributes) == sr.Attr && sr.Name != "." && sr.Name != "..")
            {
//				dataSize += CalculateDirSize(productDir + "\\" + sr.Name);
				dataSize += 1024*1024*1024;
			}
		} while (FindNext(sr) == 0);
        FindClose(sr);
    }
	return dataSize;
}
//---------------------------------------------------------------------------
__int64 __fastcall TMainForm::CalculateDirSize(AnsiString dir)
{
	__int64 dataSize = 0;
	TSearchRec sr;
    int iAttributes = faAnyFile;
    if (FindFirst(dir + "\\*.*", iAttributes, sr) == 0)
    {
    	do
        {
        	if (sr.Name == "." || sr.Name == "..") continue;
        	if ((sr.Attr & faDirectory))
            {
	            dataSize += CalculateDirSize(dir + "\\" + sr.Name);
            }
            else
            {
            	AnsiString sourceFileName = dir + "\\" + sr.Name;
			    TFileStream *fileStream = new TFileStream(sourceFileName, fmOpenRead);
			    if (fileStream)
			    {
			    	dataSize += fileStream->Size;
					delete fileStream;
			    }
            }
        } while (FindNext(sr) == 0);
        FindClose(sr);
    }
    return dataSize;
}
//---------------------------------------------------------------------------
AnsiString __fastcall TMainForm::GetDataSizeStr(__int64 dataSize)
{
    if (dataSize > 1024)
    {
		double dataSizeK = dataSize / 1024.0;
        if (dataSizeK > 1024)
        {
			double dataSizeM = dataSizeK / 1024.0;
            if (dataSizeM > 1024)
            {
				double dataSizeG = dataSizeM / 1024.0;
                return (FloatToStrF(dataSizeG, ffFixed, 5, 2) + " GB");
            }
            else
            {
	            return (FloatToStrF(dataSizeM, ffFixed, 5, 2) + " MB");
            }
        }
        else
        {
	        return (FloatToStrF(dataSizeK, ffFixed, 5, 2) + " KB");
        }
    }
    else
    {
	    return (IntToStr(dataSize) + " Bytes");
    }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::DeleteBackupDataButtonClick(TObject *Sender)
{
	if (MessageDlgFA("정말 삭제하겠습니까?", mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
	{
		AnsiString backupDir = BackupInfoList[RestoreStringGrid->Row - 1].Dir;
		RemoveAll(backupDir);
	}
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RemoveAll(AnsiString folder)
{
	TSearchRec sr;
	int iAttributes = faAnyFile;
	if (FindFirst(folder + "\\*.*", iAttributes, sr) == 0)
	{
		do
		{
			if (sr.Name == "." || sr.Name == "..") continue;
			if (sr.Attr & faDirectory)
			{
				RemoveAll(folder + "\\" + sr.Name);
			}
			else
			{
				DeleteFile(folder + "\\" + sr.Name);
			}
		} while (FindNext(sr) == 0);
		FindClose(sr);
	}
	RemoveDir(folder);

    RefreshBackupList();
    RefreshRestoreStringGrid();	
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::BCProductInfoCheckBoxClick(TObject *Sender)
{
	RefreshBackupPanel();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RefreshBackupPanel(void)
{
	if (BCProductInfoCheckBox->Checked)
	{
		IncludeTabletImageCheckBox->Enabled = true;
	}
	else
	{
		IncludeTabletImageCheckBox->Enabled = false;
	}
}
//---------------------------------------------------------------------------

