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

#include <vcl.h>
#include <inifiles.hpp>
#include <stdio.h>
#include <iostream.h>
using namespace std;
#include <inifiles.hpp>
#pragma hdrstop

#include "UserRegister_Form.h"
#include "Environment.h"
#include "Main_Form.h"
#include "Message_Form.h"
#include "Keyboard_Form.h"
#include "MultiLanguage.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntButtons"
#pragma link "TntExtCtrls"
#pragma link "TntStdCtrls"
#pragma link "TntGrids"
#pragma resource "*.dfm"

#define SELECTED_PANEL_NONE             -1
#define SELECTED_PANEL_MODIFY           0
#define SELECTED_PANEL_DELETE           1
#define SELECTED_PANEL_REGISTRATION     2
#define SELECTED_PANEL_MODIFYGRADE      3
#define SELECTED_PANEL_USERUNLOCK       4
#define SELECTED_PANEL_USERACTIVE       5

TUser User;

TUserRegisterForm *UserRegisterForm;
//---------------------------------------------------------------------------
__fastcall TUserRegisterForm::TUserRegisterForm(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);
  }

	selectedPanel = SELECTED_PANEL_NONE;
	InitializeUserData();
	userExist = true;

	int Categorynumber = 0;

	if(ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_REGIST] &&
      ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_DELETE])
  {
    // 아이디의 등록과 삭제를 관여하는 유저를 관리자로 정의하고 비밀번호 잠김해제 권한 부여
		UserUnlockButton->Visible = true;
	}
	else
	{
		UserUnlockButton->Visible = false;
	}

  if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_REGIST])
		RegistrationSpeedButton->Enabled = true;
	else
		RegistrationSpeedButton->Enabled = false;

	if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_DELETE])
		DeleteSpeedButton->Enabled = true;
	else
		DeleteSpeedButton->Enabled = false;

	if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_CHANGE_PW])
		ModifySpeedButton->Enabled = true;
	else
		ModifySpeedButton->Enabled = false;

	CurrentUserRemoved = false;

  MsgList[0] = USERRESISTERFORM_LABEL_CAPTION_10;
  MsgList[1] = USERRESISTERFORM_LABEL_CAPTION_11;
  MsgList[2] = USERRESISTERFORM_LABEL_CAPTION_12;
  MsgList[3] = USERRESISTERFORM_LABEL_CAPTION_13;
  MsgList[4] = USERRESISTERFORM_LABEL_CAPTION_14;
  MsgList[5] = USERRESISTERFORM_LABEL_CAPTION_15;
  MsgList[6] = USERRESISTERFORM_LABEL_CAPTION_16;
  MsgList[7] = USERRESISTERFORM_LABEL_CAPTION_17;
  MsgList[8] = USERRESISTERFORM_LABEL_CAPTION_18;
  MsgList[9] = USERRESISTERFORM_LABEL_CAPTION_19;
  MsgList[10] = USERRESISTERFORM_LABEL_CAPTION_20;

	AuthorityListGrid->RowCount = MAX_UI_ACCESS_EVENT + 1;
	AuthorityListGrid->ColWidths[0] = 265;
	AuthorityListGrid->ColWidths[1] = 100;
	AuthorityListGrid->Cells[0][0] = USERRESISTERFORM_LABEL_CAPTION_08;
	AuthorityListGrid->Cells[1][0] = COMPUTERSYSTEMSETTINGFORM_LABEL_CAPTION_21;

  for(int EventID = 0; EventID < MAX_UI_ACCESS_EVENT; EventID++)
  {
    AuthorityListGrid->Cells[0][EventID + 1] = ProgramAccessAuthorityData.ProgramAccessEventDescription[EventID];
  }

	GetDefaultString();
	ShowAuthority(0);
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::GetDefaultString()
{
	RegistrationApplyBitBtn->Caption = USERRESISTERFORM_BITBTN_CAPTION_01;
	CloseBitBtn->Caption = USERRESISTERFORM_BITBTN_CAPTION_02;
	RegistrationSpeedButton->Caption = USERRESISTERFORM_BUTTON_CAPTION_01;

	this->Caption = USERRESISTERFORM_FORM_CAPTION_01;
	Label15->Caption = USERRESISTERFORM_LABEL_CAPTION_01;
	Label16->Caption = USERRESISTERFORM_LABEL_CAPTION_02;
	Label9->Caption = USERRESISTERFORM_LABEL_CAPTION_03;
	Label14->Caption = USERRESISTERFORM_LABEL_CAPTION_04;
	Label19->Caption = USERRESISTERFORM_BUTTON_CAPTION_01;
	Label18->Caption = USERRESISTERFORM_LABEL_CAPTION_06;
	RegistrationGradeRadioGroup->Caption = USERRESISTERFORM_RADIOGROUP_CAPTION_01;
  UserUnlockButton->Caption = USERRESISTERFORM_BITBTN_CAPTION_03;
  if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
    DeleteSpeedButton->Caption = "Active/DeActive User";
  else
    DeleteSpeedButton->Caption = USERRESISTERFORM_BUTTON_CAPTION_02;

  UnlockBitBtn->Caption = USERRESISTERFORM_BITBTN_CAPTION_04;
  TntLabel1->Caption = USERRESISTERFORM_BITBTN_CAPTION_03;

	DeleteApplyBitBtn->Caption = INSPECTIONRESULTINSERTFORM_LABEL_CAPTION_20;
	ModifyApplyBitBtn->Caption = INSPECTIONRESULTINSERTFORM_LABEL_CAPTION_36;

	//Add
	ModifySpeedButton->Caption = USERRESISTERFORM_LABEL_CAPTION_03;
	Label11->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_05;
	Label13->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_03;
	Label8->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_01;
	Label1->Caption = USERRESISTERFORM_LABEL_CAPTION_07;
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::InitializeUserData(void)
{
	UserList.clear();
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
	if (iniFile)
	{
		TStringList *sectionList = new TStringList;
		iniFile->ReadSections(sectionList);
		int userCount = iniFile->ReadInteger("Information", "Count", 0);

		for (int userIndex = 0; userIndex < sectionList->Count; userIndex++)
		{
			AnsiString id = sectionList->Strings[userIndex];
			TUser anUser;
			anUser.Index = userIndex;
			anUser.ID = id;
			anUser.Password = iniFile->ReadString(id, "Password", "DEFAULT#PASS");
			anUser.AccessLevel = iniFile->ReadInteger(id, "Access Level", SYSTEM_ACCESS_LEVEL_ANONYMOUS);
			anUser.FirstLogin = iniFile->ReadBool(id, "FirstLogin", false);
      anUser.AcDeactive = iniFile->ReadBool(id, "AcDeactive", false);

			// 현재 작업자가 관리자라면
			if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_REGIST] &&
          ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_DELETE])
			{
				anUser.Editable = true;
			}
			else
			{
				anUser.Editable = false;
			}

			UserList.push_back(anUser);
		}

		delete sectionList;
		delete iniFile;
	}
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ModifySpeedButtonClick(TObject *Sender)
{
	selectedPanel = SELECTED_PANEL_MODIFY;
	ModifyPanels();
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ModifyPanels(void)
{
	switch (selectedPanel)
	{
	case SELECTED_PANEL_MODIFY:
		ModifyPanel->Visible = true;
		DeletePanel->Visible = false;
		RegistrationPanel->Visible = false;
		RightPanel->Visible = false;
		UserUnlockPanel->Visible = false;
    ActiveUserPanel->Visible = false;
		//this->Width = 550;//550
		break;

	case SELECTED_PANEL_DELETE:
		ModifyPanel->Visible = false;
		DeletePanel->Visible = true;
		RegistrationPanel->Visible = false;
		ModifyDeletePanel();
		RightPanel->Visible = false;
		UserUnlockPanel->Visible = false;
    ActiveUserPanel->Visible = false;
		//this->Width = 770;
		break;

	case SELECTED_PANEL_REGISTRATION:
		ModifyPanel->Visible = false;
		DeletePanel->Visible = false;
		RegistrationPanel->Visible = true;
		UserUnlockPanel->Visible = false;
		ModifyRegistPanel();
		RightPanel->Visible = true;
    ActiveUserPanel->Visible = false;

		//this->Width = 900;
		break;

	case SELECTED_PANEL_USERUNLOCK:
		ModifyPanel->Visible = false;
		DeletePanel->Visible = false;
		RegistrationPanel->Visible = false;
		ModifyUserUnlockPanel();
		RightPanel->Visible = false;
		UserUnlockPanel->Visible = true;
    ActiveUserPanel->Visible = false;
		//this->Width = 810;
		break;

  case SELECTED_PANEL_USERACTIVE:
    ModifyPanel->Visible = false;
		DeletePanel->Visible = false;
		RegistrationPanel->Visible = false;
		RightPanel->Visible = false;
		UserUnlockPanel->Visible = false;
    ActiveUserPanel->Visible = true;
    ModifyUserActivePanel();
    //this->Width = 900;
    break;

	default:
		ModifyPanel->Visible = false;
		DeletePanel->Visible = false;
		RegistrationPanel->Visible = false;
		RightPanel->Visible = false;
		UserUnlockPanel->Visible = false;
    ActiveUserPanel->Visible = false;
		//this->Width = 900;
		break;
	}

	this->Position = poMainFormCenter;
}
//------------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ModifyDeletePanel(void)
{
	int Additional_Line = 2;

	DeleteListStringGrid->RowCount = Additional_Line;
	DeleteListStringGrid->Cells[0][0] = USERRESISTERFORM_LABEL_CAPTION_04;
	DeleteListStringGrid->Cells[1][0] = USERRESISTERFORM_RADIOGROUP_CAPTION_01;
	DeleteListStringGrid->Cells[0][1] = "system";
	DeleteListStringGrid->Cells[1][1] = "System Engineer";

  DeleteListStringGrid->ColWidths[0] = 600;
  DeleteListStringGrid->ColWidths[0] = 400;

	if (UserList.size() > 0)
	{
		DeleteListStringGrid->RowCount = UserList.size() + Additional_Line;
	}

	vector<TUser>::iterator it;
	int rowIndex = Additional_Line;
	for (it = UserList.begin(); it != UserList.end(); ++it)
	{
		if (it->Editable)
		{
      DeleteListStringGrid->Cells[0][rowIndex] = it->ID;
			int userLevel = it->AccessLevel;

      if(userLevel == SYSTEM_ACCESS_LEVEL_ANONYMOUS || !(userLevel >= 1 && userLevel < MAX_AUTHORITY_COUNT))
      {
        DeleteListStringGrid->Cells[1][rowIndex] = USER_AUTHORITY_SETTING_FORM_TEXT_03;
      }
      else
      {
        if(userLevel >= ProgramAccessAuthorityData.SystemAuthorityCount)
        {
          DeleteListStringGrid->Cells[1][rowIndex] = USER_AUTHORITY_SETTING_FORM_TEXT_03;
        }
        else
        {
          DeleteListStringGrid->Cells[1][rowIndex] = ProgramAccessAuthorityData.ProgramAccessAuthorityName[userLevel];
        }
      }

			rowIndex++;
		}
	}
	if (UserList.size() == 0)
	{
		DeleteSelectedIndex = -1;
	}
	else
	{
		DeleteSelectedIndex = 0;
		DeleteListStringGrid->Row = 1;
	}
	DisplayDeleteEdit();
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ModifyRegistPanel(void)
{
	RegistrationIDEdit->Text = "";
	RegistrationPasswordEdit->Text = "";
	RegistrationPasswordConfirmEdit->Text = "";
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::DisplayModifyEdit(void)
{
	ModifyOldPasswordEdit->Text = "";
	ModifyNewPasswordEdit->Text = "";
	ModifyNewRecheckEdit->Text = "";
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::DisplayDeleteEdit(void)
{
	if (DeleteSelectedIndex >= 0 && DeleteSelectedIndex < DeleteListStringGrid->RowCount - 1)
	{
		DeleteIDEdit->Text = DeleteListStringGrid->Cells[0][DeleteSelectedIndex + 1];
		if (DeleteSelectedIndex == 0)
			DeleteApplyBitBtn->Enabled = false;
		else
			DeleteApplyBitBtn->Enabled = true;
	}
	else
	{
		DeleteIDEdit->Text = "";
	}
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::FormDestroy(TObject *Sender)
{
	UserList.clear();
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::RegistrationApplyBitBtnClick(
	TObject *Sender)
{
	AnsiString newID = RegistrationIDEdit->Text;
	AnsiString newPassword = "";
	AnsiString confirmedPassword = "";

	if(PCProgramOption.CareUpperLowCasePasswordEnabled)
	{
		newPassword = RegistrationPasswordEdit->Text;
		confirmedPassword = RegistrationPasswordConfirmEdit->Text;
	}
	else
	{
		newPassword = RegistrationPasswordEdit->Text.LowerCase();
		confirmedPassword = RegistrationPasswordConfirmEdit->Text.LowerCase();
	}
	
	int userEventAccessLevel = RegistrationGradeRadioGroup->ItemIndex + 1;

	if (newID == "SYSTEM")
	{
		ShowMessageFA(MsgList[4]);
		return;
	}

	try
	{
		//UserList.clear();
		TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
		if (iniFile)
		{
			TStringList *sectionList = new TStringList;
			iniFile->ReadSections(sectionList);
			//int userCount = iniFile->ReadInteger("Information","Count", 0);
			if (sectionList->Count > 500)
			{
				throw Exception(MsgList[7]);
			}
		}
		delete iniFile;

		if (!newID.Length())
		{
			throw Exception(MsgList[0]);
		}
    else
    {
      int textLength = newID.Length();
      if( textLength > 32 )
      {
        char *strBuff = new char[textLength + 1];
        memset(strBuff, 0, sizeof(char) * textLength + 1);
        strcpy(strBuff, newID.c_str());

         if(strBuff[31] & 0x80)
         {
            AnsiString CutID = newID.SubString(0,30);
            throw Exception(MsgList[10] + "  "+CutID);
         }


      }
    }

		if (!newPassword.Length())
		{
			throw Exception(MsgList[1]);
		}
		if (newPassword.Length() < ComputerSystemInfo.PasswordMinLength)
		{
			WCHAR TmpStr[100];

			wsprintfW(TmpStr, USERRESISTERFORM_MSG_08, ComputerSystemInfo.PasswordMinLength);
			throw Exception(TmpStr);
		}
		/// test khs
		if (newPassword.Length())
		{
			AnsiString fisrtKeyShiftStr[] = { "~", "!", "@", "#", "$", "%", "^",
				"&", "*", "(" , ")", "-", "+", "=", ";", ":", "'", "," ,"." ,"?" ,"/" ,"<" ,">" };
			AnsiString NumberStr[] = { "0","1","2","3","4","5","6","7","8","9" };

			char newpwsize = newPassword.Length();
			char *NewPW = new char[newpwsize + 1];
			char SpecialCharacter[23];
			char Number[10];

			strcpy(NewPW, newPassword.c_str());
			for (int k = 0; k < 23; k++)
			{
				strcpy(&SpecialCharacter[k], fisrtKeyShiftStr[k].c_str());
			}
			for (int y = 0; y < 10; y++)
			{
				strcpy(&Number[y], NumberStr[y].c_str());
			}
			if (strpbrk(NewPW, SpecialCharacter) == NULL)
			{
				//throw Exception("Passwords must contain special characters.(ex.~!@#...)");
				throw Exception(MsgList[2]);
			}
			else
			{
				if (strpbrk(NewPW, Number) == NULL)
				{
					throw Exception(MsgList[5]);
				}
				else
				{
					int j = newPassword.Length();
					int ok = 0;

					if(PCProgramOption.CareUpperLowCasePasswordEnabled)
					{
						for (int l = 0; l < j; l++)
						{
							if ((0x41 <= NewPW[l]) && (NewPW[l] <= 0x5a) || (0x61 <= NewPW[l]) && (NewPW[l] <= 0x7a)) 
							{
								ok = 1;
							}
						}
					}
					else
					{
						for (int l = 0; l < j; l++)
						{
							if ( (0x61 <= NewPW[l]) && (NewPW[l] <= 0x7a)) 
							{
								ok = 1;
							}
						}					
					}

					if (!ok)
					{
						throw Exception(MsgList[6]);
					}
				}
			}
		}
		/// test khs
		if (newPassword != confirmedPassword)
		{
			throw Exception(MsgList[3]);
		}
		if (IsExistID(RegistrationIDEdit->Text))
		{
			throw Exception(MsgList[4]);
		}

		if (RegisterNewID(newID, newPassword, userEventAccessLevel))
		{
      WriteLastPassword(newID, newPassword);

			WCHAR TempString[1000];

			wsprintfW(TempString, USERRESISTERFORM_MSG_14, WideString(newID));
			ShowMessageFA(WideString(TempString));
			AddCSVActionLog(ECSV_ACTION_USER_ADD, UserInfo.Name, "", newID.c_str(), newID.Length() + 1);
			ModifyRegistPanel();
		}
	}
	catch (Exception &ec)
	{
		ShowMessageFA(ec.Message);
	}
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::RegistrationIDEditClick(TObject *Sender)
{
  // 셀트리온 요청으로 인한 LowerCase 변경 
	TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
  KeyboardForm->JP_IDInputKeyBoard = true;
	if (KeyboardForm->ShowKeyboard() == mrOk)
	{
		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::PasswordEditClick(
	TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowPasswordKeyboard() == mrOk)
	{
		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------
bool __fastcall TUserRegisterForm::IsExistID(AnsiString newID)
{
	vector<TUser>::iterator it;
	for (it = UserList.begin(); it != UserList.end(); ++it)
	{
		if (newID == it->ID)
		{
			return true;
		}
	}
	return false;
}
//---------------------------------------------------------------------------
bool __fastcall TUserRegisterForm::RegisterNewID(AnsiString id, AnsiString password, int AccessLevel)
{
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
	if (iniFile)
	{
		iniFile->WriteString(id, "Password", TextToPassword(password));
		iniFile->WriteFloat(id, "Password Change Time", Now().Val);
		iniFile->WriteInteger(id, "Access Level", AccessLevel);
		iniFile->WriteBool(id, "FirstLogin", false);
		delete iniFile;
		InitializeUserData();
	}
	else
	{
		throw Exception(USERRESISTERFORM_MSG_01);
	}

	return true;
}
//---------------------------------------------------------------------------
bool __fastcall TUserRegisterForm::DeleteID(AnsiString id)
{
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
	if (iniFile)
	{
		iniFile->EraseSection(id);
		delete iniFile;
		InitializeUserData();
		ModifyPanels();
	}
	else
	{
		throw Exception(USERRESISTERFORM_MSG_09);
	}
	return true;
}

//---------------------------------------------------------------------------
bool __fastcall TUserRegisterForm::ChangePassword(AnsiString id, AnsiString password)
{
	if (id == "system")
	{
		AnsiString fileName;
		fileName = ProgramPath.Env + "\\systemUser.dat";

		TFileStream *pFileStream = new TFileStream(fileName, fmCreate);

		int passwordLength = password.Length();
		pFileStream->Write(&passwordLength, sizeof(int));
		pFileStream->Write(password.c_str(), sizeof(char) * passwordLength);

		delete pFileStream;
	}
	else
	{
		TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");

		if (iniFile)
		{
			iniFile->WriteString(UserInfo.Name, "Password", TextToPassword(password));
			iniFile->WriteFloat(UserInfo.Name, "Password Change Time", Now().Val);
			delete iniFile;
			InitializeUserData();
		}
		else
		{
			throw Exception(USERRESISTERFORM_MSG_02);
		}
	}
	return true;
}
//---------------------------------------------------------------------------
AnsiString __fastcall PasswordToText(AnsiString password)
{
	int length = password.Length();
	AnsiString text = "";
	for (int i = 0; i < length; i++)
	{
		char temp;

		temp = *password.SubString(i + 1, 1).c_str();
		text += (char)(temp - PASSWORD_ADD_VALUE);

	}

	return text;
}
//---------------------------------------------------------------------------
AnsiString __fastcall TextToPassword(AnsiString text)
{
	int length = text.Length();
	AnsiString password = "";
	for (int i = 0; i < length; i++)
	{
		char temp;

		temp = *text.SubString(i + 1, 1).c_str();
		password += (char)(temp + PASSWORD_ADD_VALUE);

	}

	return password;
}
//---------------------------------------------------------------------------
int __fastcall CheckUserNameAndPassword(AnsiString id, AnsiString password)
{
	int returnValue = -1;

	if (id == "system")
	{
		AnsiString fileName;
		fileName = ProgramPath.Env + "\\systemUser.dat";

		if (FileExists(fileName))
		{
			TFileStream *pFileStream = new TFileStream(fileName, fmOpenRead);

			int passwordLength;
			pFileStream->Read(&passwordLength, sizeof(int));

			char *existPW = new char[passwordLength];
			memset(existPW, 0, sizeof(char) * passwordLength);

			for (int i = 0; i < passwordLength; i++)
			{
				pFileStream->Read(&existPW[i], sizeof(char));
			}

			char tempLoadPassword[100];
			memset(tempLoadPassword, 0, sizeof(char) * 100);
			memcpy(tempLoadPassword, existPW, passwordLength);

			AnsiString tempPW = AnsiString(tempLoadPassword);

			if (password == tempPW)
			{
				returnValue = 0;
			}
			else
			{
				returnValue = -1;
			}

			delete existPW;
			delete pFileStream;
		}
		else
		{
			if (password == "111111")
				returnValue = 0;
			else
				returnValue = -1;
		}
	}
	else
	{
		TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
		if (iniFile)
		{
			if (iniFile->SectionExists(id))
			{
				AnsiString correctPassword = PasswordToText(iniFile->ReadString(id, "Password", ""));
				if (password == correctPassword)
				{
					returnValue = 0;
				}
				else
				{
					returnValue = -3;
				}
			}
			else
			{
				returnValue = -2;
			}
			delete iniFile;
		}
	}

	return returnValue;
}
//---------------------------------------------------------------------------
bool __fastcall CheckPasswordExpiration(AnsiString id, double timeLimit)
{
	bool returnValue = true;
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
	if (iniFile)
	{
		double passwordChangeTime = iniFile->ReadFloat(id, "Password Change Time", 0);
		if (timeLimit > Now().Val - passwordChangeTime)
		{
			returnValue = false;
		}

		delete iniFile;
	}
	return returnValue;
}
//---------------------------------------------------------------------------
bool __fastcall LoadUserInfo(AnsiString id)
{
	bool returnValue = false;
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
	if (iniFile)
	{
		if (iniFile->SectionExists(id))
		{
			UserInfo.Name = id;
			UserInfo.AccessLevel = iniFile->ReadInteger(id, "Access Level", SYSTEM_ACCESS_LEVEL_ANONYMOUS);
			returnValue = true;
		}
		else
		{
			returnValue = false;
		}
		delete iniFile;
	}

	return returnValue;
}

//--------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ShowAuthority(int AccessLevel)
{
  for(int EventID = 0; EventID < MAX_UI_ACCESS_EVENT; EventID++)
	{
    if(ProgramAccessAuthorityData.ProgramAccessAuthorityTable[AccessLevel][EventID])
		  AuthorityListGrid->Cells[1][EventID + 1] = USERRESISTERFORM_LABEL_CAPTION_09;
    else
      AuthorityListGrid->Cells[1][EventID + 1] = "";
	}
}
//------------------------------------------------------------------------
void __fastcall TUserRegisterForm::DeleteSpeedButtonClick(TObject *Sender)
{
  if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE2)
    selectedPanel = SELECTED_PANEL_USERACTIVE;
  else
	  selectedPanel = SELECTED_PANEL_DELETE;
    
	ModifyPanels();
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::DeleteApplyBitBtnClick(TObject *Sender)
{
	if (DeleteSelectedIndex >= 0 && DeleteIDEdit->Text != NULL)
	{
		AnsiString deleteID = DeleteIDEdit->Text;
		WCHAR TmpStr[100];
		wsprintfW(TmpStr, USERRESISTERFORM_MSG_13, WideString(deleteID));
		if (MessageDlgFA(WideString(TmpStr), mtError, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
		{
			try
			{
				if (DeleteID(deleteID))
				{
					//					ClientPanel->Caption = "작업자 삭제 완료: " + deleteID;
					if (deleteID == UserInfo.Name)
					{
						CurrentUserRemoved = true;
						ModalResult = mrCancel;
					}

					AddCSVActionLog(ECSV_ACTION_USER_DELETE, UserInfo.Name, "", deleteID.c_str(), deleteID.Length() + 1);

          _DeleteReg("SOFTWARE\\NFA",deleteID.LowerCase().c_str()); // 로그인 실패 관련 초기화
				}
			}
			catch (Exception &ec)
			{
				ShowMessageFA(ec.Message);
			}
		}
	}
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ModifyApplyBitBtnClick(TObject *Sender)
{
	try
	{
		AnsiString oldPassword = "";
		AnsiString newPassword =  "";
		AnsiString confirmedPassword = "";

		if(PCProgramOption.CareUpperLowCasePasswordEnabled)
		{
			oldPassword = ModifyOldPasswordEdit->Text;
			newPassword = ModifyNewPasswordEdit->Text;
			confirmedPassword = ModifyNewRecheckEdit->Text;
		}
		else
		{
			oldPassword = ModifyOldPasswordEdit->Text.LowerCase();
			newPassword = ModifyNewPasswordEdit->Text.LowerCase();
			confirmedPassword = ModifyNewRecheckEdit->Text.LowerCase();
		}		
		
		if (oldPassword == "")
		{
			ShowMessageFA(USERRESISTERFORM_MSG_15);
			return;
		}
		if (newPassword == "")
		{
			ShowMessageFA(USERRESISTERFORM_MSG_10);
			return;
		}
		if (newPassword.Length())
		{
			AnsiString fisrtKeyShiftStr[] = { "~", "!", "@", "#", "$", "%", "^",
				"&", "*", "(" , ")", "-", "+", "=", ";", ":", "'", "," ,"." ,"?" ,"/" ,"<" ,">" };

			char NewPW[15];
			char SpecialCharacter[23];

			strcpy(NewPW, newPassword.c_str());
			for (int k = 0; k < 23; k++)
			{
				strcpy(&SpecialCharacter[k], fisrtKeyShiftStr[k].c_str());
			}
			if (strpbrk(NewPW, SpecialCharacter) == NULL)
			{
				//throw Exception("Passwords must contain special characters.(ex.~!@#...)");
				ShowMessageFA(MsgList[2]);
				return;
			}
		}
		if (newPassword.Length() < ComputerSystemInfo.PasswordMinLength)
		{
			WCHAR TmpStr[100];
			wsprintfW(TmpStr, USERRESISTERFORM_MSG_08, ComputerSystemInfo.PasswordMinLength);
			ShowMessageFA(TmpStr);
			return;
		}
		if (confirmedPassword == "")
		{
			ShowMessageFA(USERRESISTERFORM_MSG_05);
			return;
		}
		if (newPassword != confirmedPassword)
		{
			ShowMessageFA(USERRESISTERFORM_MSG_04);
			return;
		}
		if (newPassword == oldPassword)
		{
			ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_07);
			return;
		}
		if (CheckUserNameAndPassword(UserInfo.Name, oldPassword) == 0)
		{
      if(UserInfo.Name != "system")
      {
        if (CheckLastPassword(UserInfo.Name, newPassword))
        {
          ShowMessageFA(MsgList[9]);
          return;
        }
      }

			if (ChangePassword(UserInfo.Name, newPassword))
			{
        if(UserInfo.Name != "system")
        {
				  WriteLastPassword(UserInfo.Name, newPassword);
        }

				ShowMessageFA(USERRESISTERFORM_MSG_03);
				AddCSVActionLog(ECSV_ACTION_USER_PASSWORD_CHANGE, UserInfo.Name, "", NULL, 0);
				selectedPanel = SELECTED_PANEL_NONE;
				ModifyPanels();
			}
		}
		else
		{
			ShowMessageFA(USERRESISTERFORM_MSG_06);
			return;
		}
	}
	catch (Exception &ec)
	{
		ShowMessageFA(ec.Message);
	}
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::DeleteStringGridClick(
	TObject *Sender)
{
	DeleteSelectedIndex = DeleteListStringGrid->Row - 1;
	DisplayDeleteEdit();
}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::OnUserChange(void)
{
	selectedPanel = SELECTED_PANEL_NONE;

  if(ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_REGIST] &&
      ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_DELETE])
  {
    // 아이디의 등록과 삭제를 관여하는 유저를 관리자로 정의하고 비밀번호 잠김해제 권한 부여
		UserUnlockButton->Visible = true;
	}
	else
	{
		UserUnlockButton->Visible = false;
	}

  if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_REGIST])
		RegistrationSpeedButton->Enabled = true;
	else
		RegistrationSpeedButton->Enabled = false;

	if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_DELETE])
		DeleteSpeedButton->Enabled = true;
	else
		DeleteSpeedButton->Enabled = false;

	if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_USERRESISTERFORM_CHANGE_PW])
		ModifySpeedButton->Enabled = true;
	else
		ModifySpeedButton->Enabled = false;

	ModifyPanels();
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::RegistrationSpeedButtonClick(
	TObject *Sender)
{
	selectedPanel = SELECTED_PANEL_REGISTRATION;
	ModifyPanels();
  RegistrationGradeRadioGroup->ItemIndex = 0;
	ShowAuthority(RegistrationGradeRadioGroup->ItemIndex + 1);
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::TntFormActivate(TObject *Sender)
{
  for(int athID = 1; athID < ProgramAccessAuthorityData.SystemAuthorityCount; athID++)
  {
    RegistrationGradeRadioGroup->Items->Add(ProgramAccessAuthorityData.ProgramAccessAuthorityName[athID]);
  }

	RegistrationGradeRadioGroup->ItemIndex = 0;
	selectedPanel = SELECTED_PANEL_NONE;
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::RegistrationGradeRadioGroupClick(
	TObject *Sender)
{
	ShowAuthority(RegistrationGradeRadioGroup->ItemIndex + 1);
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::UserUnlockButtonClick(TObject *Sender)
{

  selectedPanel = SELECTED_PANEL_USERUNLOCK;
 	ModifyPanels();

}
//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ModifyUserUnlockPanel(void)
{
	UserUnlockStringGrid->RowCount = 2;
  UserUnlockStringGrid->ColWidths[0] = 310;
  UserUnlockStringGrid->ColWidths[1] = 300;
	UserUnlockStringGrid->Cells[0][0] = USERRESISTERFORM_LABEL_CAPTION_04;
	UserUnlockStringGrid->Cells[1][0] = USERRESISTERFORM_RADIOGROUP_CAPTION_01;
	UserUnlockStringGrid->Cells[0][1] = "";
	UserUnlockStringGrid->Cells[1][1] = "";
	vector<TUser>::iterator it;
	int rowIndex = 0;
	for (it = UserList.begin(); it != UserList.end(); ++it)
	{
		if (it->Editable)
		{
      if(it->ID.LowerCase() != "system")
      {
        int Check = _ReadReg("SOFTWARE\\NFA", it->ID.LowerCase().c_str());
        if (Check >= ComputerSystemInfo.PasswordFailAvailableCount
        && Check != 99999999)
        {
          ++rowIndex;
        }
      }
		}
	}

	if (rowIndex > 0)
	{
		UserUnlockStringGrid->RowCount = rowIndex + 1;
	}

	rowIndex = 1;
	for (it = UserList.begin(); it != UserList.end(); ++it)
	{
		if (it->Editable)
		{
      if(it->ID.LowerCase() != "system")
      {
        int Check = _ReadReg("SOFTWARE\\NFA", it->ID.LowerCase().c_str());
        if ( (Check >= ComputerSystemInfo.PasswordFailAvailableCount) && (Check != 99999999))
        {
          UserUnlockStringGrid->Cells[0][rowIndex] = it->ID;

          int userLevel = it->AccessLevel;

          if(userLevel == SYSTEM_ACCESS_LEVEL_ANONYMOUS)
          {
            UserUnlockStringGrid->Cells[1][rowIndex] = "None";
          }
          else
          {
            UserUnlockStringGrid->Cells[1][rowIndex] = ProgramAccessAuthorityData.ProgramAccessAuthorityName[userLevel];
          }
          
          rowIndex++;
        }
      }
		}
	}
	if (UserList.size() == 0)
	{
		UnlockSelectedIndex = -1;
	}
	else
	{
		UnlockSelectedIndex = 0;
		UserUnlockStringGrid->Row = 1;
	}
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::UserUnlockStringGridClick(
	TObject *Sender)
{
	UnlockSelectedIndex = UserUnlockStringGrid->Row - 1;
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::UnlockBitBtnClick(TObject *Sender)
{
	if (DeleteSelectedIndex >= 0)
	{
		String ID = UserUnlockStringGrid->Cells[0][UnlockSelectedIndex + 1];
    if(ID != "")
    {
		  _SetValueReg("SOFTWARE\\NFA", ID.LowerCase().c_str(), 0);
		  AddCSVActionLog(ECSV_ACTION_UNLOCK, UserInfo.Name, "", ID.c_str(), ID.Length()+1);
		  ModifyPanels();
    }
	}
}
//--------------------------------------------------------------------------
void __fastcall TUserRegisterForm::ModifyUserActivePanel(void)
{
	ActiveUserStringGrid->RowCount = 2;
  ActiveUserStringGrid->ColWidths[0] = 300;
  ActiveUserStringGrid->ColWidths[1] = 250;
  ActiveUserStringGrid->ColWidths[2] = 150;
	ActiveUserStringGrid->Cells[0][0] = USERRESISTERFORM_LABEL_CAPTION_04;
	ActiveUserStringGrid->Cells[1][0] = USERRESISTERFORM_RADIOGROUP_CAPTION_01;
  ActiveUserStringGrid->Cells[2][0] = "STATUS";
	ActiveUserStringGrid->Cells[0][1] = "";
	ActiveUserStringGrid->Cells[1][1] = "";
  ActiveUserStringGrid->Cells[2][1] = "";

	if (UserList.size() > 0)
	{
		ActiveUserStringGrid->RowCount = UserList.size()+1;
	}

 	vector<TUser>::iterator it;
	int rowIndex = 1;
	for (it = UserList.begin(); it != UserList.end(); ++it)
	{
		if (it->Editable)
		{
			ActiveUserStringGrid->Cells[0][rowIndex] = it->ID.LowerCase();

      int userLevel = it->AccessLevel;

      if(userLevel == SYSTEM_ACCESS_LEVEL_ANONYMOUS)
      {
        ActiveUserStringGrid->Cells[1][rowIndex] = "None";
      }
      else
      {
        ActiveUserStringGrid->Cells[1][rowIndex] = ProgramAccessAuthorityData.ProgramAccessAuthorityName[userLevel];
      }

      if(!it->AcDeactive)
        ActiveUserStringGrid->Cells[2][rowIndex] = "Active";
      else
        ActiveUserStringGrid->Cells[2][rowIndex] = "DeActive";

			rowIndex++;
		}
	}
}
//---------------------------------------------------------------------------
AnsiString __fastcall GetUserPassword(AnsiString ID)
{
	AnsiString retPassword = "111111";

	if (ID == "system") // lowercase
	{
		AnsiString fileName;
		fileName = ProgramPath.Env + "\\systemUser.dat";

		if (FileExists(fileName))
		{
			TFileStream *pFileStream = new TFileStream(fileName, fmOpenRead);

			int passwordLength;
			pFileStream->Read(&passwordLength, sizeof(int));

			char *existPW = new char[passwordLength];
			memset(existPW, 0, sizeof(char) * passwordLength);

			for (int i = 0; i < passwordLength; i++)
			{
				pFileStream->Read(&existPW[i], sizeof(char));
			}

			char tempLoadPassword[100];
			memset(tempLoadPassword, 0, sizeof(char) * 100);
			memcpy(tempLoadPassword, existPW, passwordLength);

			retPassword = AnsiString(tempLoadPassword);

			delete existPW;
			delete pFileStream;
		}
		else
		{
			retPassword = "111111";
		}
	}
	else if (ID == "machine")
	{
		retPassword = "777777";
	}
	else
	{
		TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");

		if (iniFile)
		{
			if (iniFile->SectionExists(ID))
			{
				retPassword = PasswordToText(iniFile->ReadString(ID, "Password", ""));
			}
		}

		delete iniFile;
	}

	return retPassword;
}

//---------------------------------------------------------------------------
void __fastcall TUserRegisterForm::WriteLastPassword(String section, String password)
{
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
	int Result = 0;

	if (iniFile)
	{
		// PasswordToText
		while (true)
		{
			String LastPwstr = iniFile->ReadString(section, "LastPassword" + IntToStr(Result), "");
			if (LastPwstr != "")
			{
				++Result;
			}
			else
			{
				LastPwstr = TextToPassword(password);
				iniFile->WriteString(section, "LastPassword" + IntToStr(Result), LastPwstr);
				break;
			}
		}

	}
	delete iniFile;
}

//---------------------------------------------------------------------------
int __fastcall TUserRegisterForm::CheckLastPassword(String section, String password)
{
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");
	int Result = 0;
	int Count = 0;

	if (iniFile)
	{
		while (true)
		{
			String LastPwstr = iniFile->ReadString(section, "LastPassword" + IntToStr(Count), "");
			if (LastPwstr != "")
			{
				if (password == PasswordToText(LastPwstr))
				{
					Result = 1;
					break;
				}
				else
				{
					++Count;
				}
			}
			else
			{
				break;
			}
		}
	}
	delete iniFile;
	return Result;
}

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




void __fastcall TUserRegisterForm::ActiveUserStringGridClick(
      TObject *Sender)
{
  if(ActiveUserStringGrid->Row -1 != -1)
  {
    if(!UserList[ActiveUserStringGrid->Row -1].AcDeactive)
    {
      ActiveBtn->Enabled = false;
      DeActiveBtn->Enabled = true;
    }
    else
    {
      ActiveBtn->Enabled = true;
      DeActiveBtn->Enabled = false;
    }
  }
  else
  {
     ActiveBtn->Enabled = false;
     DeActiveBtn->Enabled = false;
  }
}
//---------------------------------------------------------------------------

void __fastcall TUserRegisterForm::DeActiveBtnClick(TObject *Sender)
{
  int SelectRow = ActiveUserStringGrid->Row-1;
  TTntButton * Btn = (TTntButton*)Sender;
  bool ActiveFlag = false;    

  TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");

  if(Btn->Tag)
  {
    iniFile->WriteBool(UserList[SelectRow].ID,"AcDeactive",1);
    UserList[SelectRow].AcDeactive = true;
    ActiveFlag = false;
  }
  else
  {
    iniFile->WriteBool(UserList[SelectRow].ID,"AcDeactive",0);
    UserList[SelectRow].AcDeactive = false;
    ActiveFlag = true;
  }

  delete iniFile;

   // AddCSVActionLog(ECSV_ACTION_CHANGE_ACTIVE, UserInfo.Name, "", (UserList[SelectRow].ID+IntToStr(Btn->Tag)).c_str(), (UserList[SelectRow].ID+IntToStr(Btn->Tag)).Length() + 1);
  if(ActiveFlag == true)
  {
		AddCSVActionLog(ECSV_ACTION_CHANGE_ACTIVE, UserInfo.Name, "", (UserList[SelectRow].ID + IntToStr(Btn->Tag)).c_str(), (UserList[SelectRow].ID + IntToStr(Btn->Tag)).Length() + 1);  
  }
  else
  {
		AddCSVActionLog(ECSV_ACTION_CHANGE_DEACTIVE, UserInfo.Name, "", (UserList[SelectRow].ID + IntToStr(Btn->Tag)).c_str(), (UserList[SelectRow].ID + IntToStr(Btn->Tag)).Length() + 1);  
  }

  ModifyUserActivePanel();
  ActiveUserStringGrid->Row = SelectRow+1;
}
//---------------------------------------------------------------------------

