// ChangePasswordDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChangePasswordDlg.h"
#include <aplBaseLib.h>
//#include <math.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CChangePasswordDlg dialog


CChangePasswordDlg::CChangePasswordDlg(bool bAdmin, CaplAPI *api, CWnd* pParent /*=NULL*/)
	: m_cSecurity(api), CaplTranslateDialog(CChangePasswordDlg::IDD, pParent)
{
	ASSERT(api);
	m_api = api;

	m_pUser= NULL;
	m_bAdmin = bAdmin;
}


CChangePasswordDlg::~CChangePasswordDlg()
{
}

void CChangePasswordDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CChangePasswordDlg)
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_NEW_PASS, m_new_pass_ctrl);
	DDX_Control(pDX, IDC_RESET_PASSWORD, m_reset_btn);
	DDX_Control(pDX, IDC_SET_SECURITY, m_set_security_btn);
	DDX_Control(pDX, IDC_ICO_CORRECT, m_st_ico_correct);
	DDX_Control(pDX, IDC_ICO_CORRECT2, m_st_ico_correct2);
	DDX_Control(pDX, IDC_NEW_PASS2, m_new_pass2_ctrl);
	DDX_Control(pDX, IDC_OLD_PASS, m_old_pass_ctrl);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CChangePasswordDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CChangePasswordDlg)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_RESET_PASSWORD, &CChangePasswordDlg::OnBnClickedResetPassword)
	ON_BN_CLICKED(IDC_SET_SECURITY, &CChangePasswordDlg::OnBnSetSecurity)
	ON_EN_CHANGE(IDC_NEW_PASS, &CChangePasswordDlg::OnEnChangeNewPass)
	ON_EN_CHANGE(IDC_NEW_PASS2, &CChangePasswordDlg::OnEnChangeNewPass2)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChangePasswordDlg message handlers

void CChangePasswordDlg::OnOK() 
{
	CString new_pass,new_pass2;
	m_new_pass_ctrl.GetWindowText(new_pass);
	m_new_pass2_ctrl.GetWindowText(new_pass2);

	if (new_pass.IsEmpty() && new_pass2.IsEmpty())
	{
		// ЯАИ Считаем что путой пароль может вводить только администратор,
		// но пусть для этого нажимает кнопку "Сброс". 
		AfxMessageBox(APL_T("Введите пароль!"),MB_ICONWARNING);
		//CaplTranslateDialog::OnOK();
		return;
	}

	// TODO: Add extra validation here
	//UpdateData(TRUE);

	CaplInstance* user=m_pUser;
	if(m_pUser==NULL)
	{
		user=m_api->m_data.GetCurrUser();
	}
	if(user==0) return;
	CaplAttr *attr= m_api->m_data.GetAttrDefinition(user->GetType(), _T("password"));

	// Чтение пароля из БД
	if(m_api->m_data.IsConnected())
	{
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		ld.AddQuery(_T('i'), user->GetId(), 0, attr, true);
		if(!ld.LoadEx()){
			if(apidata.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS){
				AfxMessageBox( APL_T("Ошибка чтения данных!"),MB_OK|MB_ICONSTOP);
			}
		}
	}

	if (!m_bAdmin) // Из администратора ILS не проверяем
	{
		CString old_pass, old_pass_in_db, old_pass_in_ctrl;
		
		m_old_pass_ctrl.GetWindowText(old_pass);
		m_api->m_data.GetAttrBN(user, _T("password"), old_pass_in_db);
		
		//if(!m_old_pass.IsEmpty())
		if(!old_pass_in_db.IsEmpty() && old_pass_in_db[0]==_T('^')){
			aplTranslateK(old_pass, old_pass_in_ctrl);
		}else{
			old_pass_in_ctrl=old_pass;
		}

		if(old_pass_in_db!=old_pass_in_ctrl && !m_bAdmin){ AfxMessageBox( APL_T("Неверный старый пароль !"),MB_OK|MB_ICONSTOP); return;}
	}

	if (!m_cSecurity.CheckPassword(new_pass))
	{
		CString sInfo = m_cSecurity.GetPasswordInfo();
		AfxMessageBox(APL_T("Пароль не удовлетворяет требованиям надежности! Пароль должен содержать: ") + sInfo);
		return;
	}

	if(new_pass!=new_pass2){ AfxMessageBox( APL_T("Новый пароль и его подтверждение не совпадают !"),MB_OK|MB_ICONSTOP); return;}

	CString new_pass_c;
	if(!new_pass.IsEmpty()) 
		aplTranslateK(new_pass, new_pass_c);
	
	CaplAdminModeProvider adminmode(&(m_api->m_data),-1, -1,DEF_SOURCE);
	m_api->m_data.PutAttrBN(user, _T("password"), new_pass_c);
	adminmode.ExitAdminMode();
	m_api->m_data.NET_SaveChanges();

	AfxMessageBox( APL_T("Пароль успешно изменен!"),MB_ICONINFORMATION);
	
	CaplTranslateDialog::OnOK();
}

BOOL CChangePasswordDlg::OnInitDialog() 
{
//	AFX_MANAGE_STATE(AfxGetStaticModuleState());
	CaplTranslateDialog::OnInitDialog();

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_ok_btn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_ok_btn.SetFlat(FALSE);
	m_reset_btn.SetFlat(FALSE);
	m_set_security_btn.SetFlat(FALSE);

	m_st_ico_correct.SetIcon(GetAplStdIco16(APLSTDICO_INCORRECT));
	m_st_ico_correct2.SetIcon(GetAplStdIco16(APLSTDICO_INCORRECT));

	//Скрыть настройки паролей
	if (!m_bAdmin)
	{
		m_set_security_btn.ShowWindow(SW_HIDE);
		m_reset_btn.ShowWindow(SW_HIDE);
	}
	else
	{
		m_old_pass_ctrl.EnableWindow(FALSE);
	}

	m_cSecurity.ReadFromOptions();

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CChangePasswordDlg::OnBnClickedResetPassword()
{
	CaplInstance* user=m_pUser;
	if(m_pUser==NULL)user=m_api->m_data.GetCurrUser();

	if(user==0) 	return;
	
	CaplAttr *attr= m_api->m_data.GetAttrDefinition(user->GetType(), _T("password"));

	// Чтение пароля из БД
	if (!m_api->m_data.IsConnected())
		return;

	CaplAdminModeProvider adminmode(&(m_api->m_data),-1, -1,DEF_SOURCE);
	m_api->m_data.PutAttr(user, attr, _T(""));
	adminmode.ExitAdminMode();
	m_api->m_data.NET_SaveChanges();

	AfxMessageBox( APL_T("Пароль успешно сброшен!"));
	EndDialog(IDOK);
	// TODO: Add your control notification handler code here
}

void CChangePasswordDlg::OnBnSetSecurity()
{
	CSecurityPasswordDlg dlg(m_api, &m_cSecurity);
	dlg.DoModal();
}
void CChangePasswordDlg::OnEnChangeNewPass(){SetCorrectIcon();}
void CChangePasswordDlg::OnEnChangeNewPass2() {SetCorrectIcon();}

void CChangePasswordDlg::SetCorrectIcon()
{
	CString sPsw,sPsw2;
	m_new_pass_ctrl.GetWindowText(sPsw);
	m_new_pass2_ctrl.GetWindowText(sPsw2);

	if(sPsw.GetLength()>0 && m_cSecurity.CheckPassword(sPsw)) m_st_ico_correct.SetIcon(GetAplStdIco16(APLSTDICO_CORRECT));
	else  m_st_ico_correct.SetIcon(GetAplStdIco16(APLSTDICO_INCORRECT));

	if(sPsw2==_T("") || sPsw!=sPsw2)m_st_ico_correct2.SetIcon(GetAplStdIco16(APLSTDICO_INCORRECT));
	else m_st_ico_correct2.SetIcon(GetAplStdIco16(APLSTDICO_CORRECT));
}
