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

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

#include "RequestPasswordChange_Form.h"
#include "Message_Form.h"
#include "UserRegister_Form.h"
#include "Environment.h"
#include "Keyboard_Form.h"
#include "MultiLanguage.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntDialogs"
#pragma link "TntExtCtrls"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TRequestPasswordChangeForm *RequestPasswordChangeForm;
//---------------------------------------------------------------------------
__fastcall TRequestPasswordChangeForm::TRequestPasswordChangeForm(TComponent* Owner, AnsiString userName , int BeforeLock)
	: 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);
  }

  GetDefaultString();
	UserName = userName;
  m_BeforUnlock = BeforeLock;

  if(m_BeforUnlock)
  {
    Label3->Visible = false;
    ModifyOldPasswordEdit->Visible = false;
    CancelButton->Visible = false;
  }
  else
  {
    Label3->Visible = true;
    ModifyOldPasswordEdit->Visible = true;
    CancelButton->Visible = true;
  }
}
//---------------------------------------------------------------------------
void __fastcall TRequestPasswordChangeForm::GetDefaultString()
{
	CancelButton->Caption = REQUESTPASSWORDCHANGEFORM_BUTTON_CAPTION_01;
	OkButton->Caption = REQUESTPASSWORDCHANGEFORM_BUTTON_CAPTION_02;
	this->Caption = REQUESTPASSWORDCHANGEFORM_FORM_CAPTION_01;
	Label5->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_01;
	Label1->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_02;
	Label4->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_03;
	Label2->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_04;
	Label3->Caption = REQUESTPASSWORDCHANGEFORM_LABEL_CAPTION_05;

  MsgList[0] = USERRESISTERFORM_LABEL_CAPTION_12;
  MsgList[1] = USERRESISTERFORM_LABEL_CAPTION_16;
  MsgList[2] = USERRESISTERFORM_LABEL_CAPTION_15;
  MsgList[3] = USERRESISTERFORM_LABEL_CAPTION_19;

}
//---------------------------------------------------------------------------
void __fastcall TRequestPasswordChangeForm::OkButtonClick(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(m_BeforUnlock)
      {
        if (newPassword == "")
        {
          ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_06);
          return;
        }
        if (newPassword.Length())
        {
          AnsiString fisrtKeyShiftStr[] = {"~", "!", "@", "#", "$", "%", "^",
          "&", "*", "(" , ")", "-", "+", "=", ";", ":", "'", "," ,"." ,"?" ,"/" ,"<" ,">"};
           AnsiString NumberStr[] = { "0","1","2","3","4","5","6","7","8","9" };

          char Number[11];

          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());
          }
          for (int y = 0; y < 11; y++)
          {
            strcpy(&Number[y], NumberStr[y].c_str());
          }
          if(strpbrk(NewPW,SpecialCharacter) == NULL)
          {
            //throw Exception("Passwords must contain special characters.(ex.~!@#...)");
            //throw Exception(MsgList[0]);
            ShowMessageFA(MsgList[0]);
            return;
          }
          else
          {
            if (strpbrk(NewPW, Number) == NULL)
            {
              ShowMessageFA(MsgList[2]);
              return;
            }
            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)
              {
                ShowMessageFA(MsgList[1]);
                return;
              }
            }
          }
        }
        if (newPassword.Length() < ComputerSystemInfo.PasswordMinLength)
        {
          WCHAR TempString[100];
          wsprintfW(TempString, REQUESTPASSWORDCHANGEFORM_MSG_05, ComputerSystemInfo.PasswordMinLength);
          ShowMessageFA(TempString);
          return;
          //throw Exception(TempString);
        }
        if (confirmedPassword == "")
        {
            ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_04);
            return;
        }

        if (newPassword != confirmedPassword)
        {
          ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_03);
          return;
        }

        if(CheckLastPassword(UserName,newPassword))
        {
          ShowMessageFA(MsgList[3]);
          return;
        }
        
        if (ChangePassword(newPassword))
        {
          WriteLastPassword(UserName,newPassword);
          ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_02);
          AddCSVActionLog(ECSV_ACTION_USER_PASSWORD_CHANGE, UserInfo.Name, "", NULL, 0);
          ModalResult = mrOk;
        }
        else
        {
          ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_08);
          return;
        }
        
      }
      else
      {
        if (oldPassword == "")
        {
          ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_09);
          return;
        }
        if (newPassword == "")
        {
          ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_06);
          return;
        }
        if (newPassword.Length())
        {
          AnsiString fisrtKeyShiftStr[] = {"~", "!", "@", "#", "$", "%", "^",
          "&", "*", "(" , ")", "-", "+", "=", ";", ":", "'", "," ,"." ,"?" ,"/" ,"<" ,">"};
           AnsiString NumberStr[] = { "0","1","2","3","4","5","6","7","8","9" };

          char Number[11];

          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());
          }
          for (int y = 0; y < 11; y++)
          {
            strcpy(&Number[y], NumberStr[y].c_str());
          }
          if(strpbrk(NewPW,SpecialCharacter) == NULL)
          {
            //throw Exception("Passwords must contain special characters.(ex.~!@#...)");
            ShowMessageFA(MsgList[0]);
            return;
          }
          else
          {
            if (strpbrk(NewPW, Number) == NULL)
            {
              ShowMessageFA(MsgList[2]);
              return;
            }
            else
            {
              int j = newPassword.Length();
              int ok = 0;
              for (int l = 0; l <= j; l++)
              {
                if ((0x61 <= NewPW[l]) && (NewPW[l] <= 0x7a))
                {
                  ok = 1;
                }
              }
              if (!ok)
              {
                ShowMessageFA(MsgList[1]);
                return;
              }
            }
          }
        }
        if (newPassword.Length() < ComputerSystemInfo.PasswordMinLength)
        {
          WCHAR TempString[100];
          wsprintfW(TempString, REQUESTPASSWORDCHANGEFORM_MSG_05, ComputerSystemInfo.PasswordMinLength);
          ShowMessageFA(TempString);
          return;
        }
        if (confirmedPassword == "")
        {
            ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_04);
            return;
        }

        if (CheckUserNameAndPassword(UserName, oldPassword) == 0)
        {
          if (newPassword != confirmedPassword)
          {
            ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_03);
            return;
          }
          if (newPassword == oldPassword)
          {
            ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_07);
            return;
          }


          if(CheckLastPassword(UserName,newPassword))
          {
            ShowMessageFA(MsgList[3]);
            return;
          }
          
          if (ChangePassword(newPassword))
          {
            WriteLastPassword(UserName,newPassword);
            ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_02);
            AddCSVActionLog(ECSV_ACTION_USER_PASSWORD_CHANGE, UserInfo.Name, "", NULL, 0);
            ModalResult = mrOk;
          }
          else
          {
            ShowMessageFA(REQUESTPASSWORDCHANGEFORM_MSG_08);
            return;
          }
        }
      }
    }
    catch (Exception &ec)
    {
        ShowMessageFA(ec.Message);
	  }
}
//---------------------------------------------------------------------------
bool __fastcall TRequestPasswordChangeForm::ChangePassword(AnsiString password)
{
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\user.ini");

	if (iniFile)
	{
		iniFile->WriteString(UserName, "Password", TextToPassword(password));
		iniFile->WriteFloat(UserName, "Password Change Time", Now().Val);
		delete iniFile;
	}
	else
	{
		throw Exception("Change failed - can't open file.");
	}
	return true;
}
//---------------------------------------------------------------------------


void __fastcall TRequestPasswordChangeForm::PasswordEditClick(
      TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *) Sender;
	TKeyboardForm *loginKeyboardForm = new TKeyboardForm(this);
	loginKeyboardForm->Text = theEdit->Text;
	if (loginKeyboardForm->ShowPasswordKeyboard() == mrOk)
	{
		theEdit->Text = loginKeyboardForm->Text;
	}
	delete loginKeyboardForm;
}

//---------------------------------------------------------------------------
void TRequestPasswordChangeForm::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 TRequestPasswordChangeForm::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;
}

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

