// DlgLogin.cpp : implementation file
//

#include "stdafx.h"
#include <sl_struct.h>
#include "aplNetStepData.h"
#include "DlgLogin.h"
#include "DlgTuneListConnections.h"
#include "TransportSocketClient.h"

#include <CaplLDAP.h>

extern bool global_process_wm_paint;


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

#define TIMER_ID_FAST 101010
#define TIMER_ID_CONST 101011
#define TIMER_TIME_FAST 100 
#define TIMER_TIME_CONST 1000 

/////////////////////////////////////////////////////////////////////////////
// CEditPwd dialog

BEGIN_MESSAGE_MAP(CEditPwd, CEdit)
	//{{AFX_MSG_MAP(CEditPwd)
	ON_WM_SETFOCUS()
	ON_WM_KEYUP()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


void CEditPwd::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	// TODO: Add your message handler code here and/or call default

	CEdit::OnKeyUp(nChar, nRepCnt, nFlags);
	if(nChar==VK_CAPITAL)CheckCapsLock();
}

void CEditPwd::OnSetFocus(CWnd* pOldWnd)
{
	CEdit::OnSetFocus(pOldWnd);
	CheckCapsLock();

	// TODO: Add your message handler code here
}


void CEditPwd::CheckCapsLock()
{
	short state=GetKeyState(VK_CAPITAL);
	if(state  != 0)
	{
		POINT point;
		CRect rect;
		GetWindowRect(&rect);
		CString str;
		GetWindowText(str);
		point=PosFromChar(str.GetLength()-1);
		ClientToScreen(&point);
		point.y=rect.bottom;
		CString tooltipText;
		tooltipText= APL_T("Caps Lock включен! Пароль может быть введен \r\n неправильно из-за нажатой клавиши Caps Lock");
		m_ToolTip.m_delay_time=100;
		m_ToolTip.Show(point.x,point.y, tooltipText);  
	}

}

/////////////////////////////////////////////////////////////////////////////
// CDlgLogin dialog


CDlgLogin::CDlgLogin(CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(CDlgLogin::IDD, pParent)
	, m_IsSaveLoginData(FALSE)
	, m_Domain(_T(""))
	, m_NumDays(10)
	, m_bIsCurrDomainUser(FALSE)
{
	//{{AFX_DATA_INIT(CDlgLogin)
	m_Pwd = _T("");
	m_StaticNameConnection = _T("");
	m_Username = _T("");
	//}}AFX_DATA_INIT
	m_cur_select_connection = 0;
	m_data = 0;
	m_type_license = _T("");
	m_started_uname = true;

	m_bExitAfterClose=false;
}

void CDlgLogin::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDlgLogin)
	DDX_Control(pDX, IDC_EDIT_PWD, m_CtrlEditPwd);
	DDX_Control(pDX, IDC_STATIC_USERNAME, m_StaticUsername);
	DDX_Control(pDX, IDC_STATIC_PASSWORD, m_StaticPassword);
	DDX_Control(pDX, IDC_STATIC_CONNECTION, m_StaticConnection);
	DDX_Control(pDX, IDOK, m_CtrlOk);
	DDX_Control(pDX, IDCANCEL, m_CtrlCancel);
	DDX_Control(pDX, IDC_TUNE, m_CtrlTune);
	DDX_Control(pDX, IDC_STATIC_LICENSE__ANNOTATION, m_StaticLicenseAnnotation);
	//DDX_Control(pDX, IDC_STATIC_LIC, m_StaticLicense);
	//DDX_Control(pDX, IDC_SELECT_TYPE_LICENZE, m_SelectTypeLicense);
	DDX_Control(pDX, IDC_EDIT_SELECT_USERNAME, m_CtrlEditSelectUsername);
	DDX_Control(pDX, IDC_SELECT_CONNECTION, m_SelectConnection);
	DDX_Control(pDX, IDC_STATIC_LOGO, m_logo);
	DDX_Text(pDX, IDC_EDIT_PWD, m_Pwd);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_STATIC_KEYBOARD_LAYOUT, m_KeyboardLayout);
	DDX_Check(pDX, IDC_CHK_SAVE, m_IsSaveLoginData);
	DDX_Text(pDX, IDC_COMBO_DOMAIN, m_Domain);
	DDX_Control(pDX, IDC_COMBO_DOMAIN, m_CmbDomain);
	DDX_Text(pDX, IDC_EDIT_NUM_DAYS, m_NumDays);
	DDV_MinMaxUInt(pDX, m_NumDays, 1, 30);
	DDX_Control(pDX, IDC_CHK_SAVE, m_CtrlSaveLoginData);
	DDX_Control(pDX, IDC_EDIT_NUM_DAYS, m_CtrlNumDays);
	DDX_Control(pDX, IDC_CHK__IS_DOMAIN, m_CtrlIsDomain);
	DDX_Check(pDX, IDC_CHK__IS_DOMAIN, m_bIsCurrDomainUser);
}


BEGIN_MESSAGE_MAP(CDlgLogin, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CDlgLogin)
	ON_BN_CLICKED(IDC_TUNE, OnTune)
	ON_CBN_EDITCHANGE(IDC_SELECT_CONNECTION, OnSelchangeSelectConnection)
	ON_CBN_SELCHANGE(IDC_SELECT_CONNECTION, OnSelchangeSelectConnection)
	ON_WM_MOVE()
	ON_STN_CLICKED(IDC_STATIC_USERNAME, OnStnClickedStaticUsername)
	ON_WM_CTLCOLOR()
	//}}AFX_MSG_MAP
	ON_WM_TIMER()
	ON_CBN_SELCHANGE(IDC_EDIT_SELECT_USERNAME, &CDlgLogin::OnCbnSelchangeEditSelectUsername)
	ON_CBN_EDITCHANGE(IDC_EDIT_SELECT_USERNAME, &CDlgLogin::OnCbnEditchangeEditSelectUsername)
	ON_BN_CLICKED(IDC_CHK__IS_DOMAIN, &CDlgLogin::OnBnClickedChk)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDlgLogin message handlers

BOOL CDlgLogin::OnInitDialog() 
{
	CaplTranslateDialog::OnInitDialog();
	if(m_data== 0)
	{
		return FALSE;
	}
	
	aplGetLogoBmp(m_bmp,this);
	m_logo.SetBitmap(HBITMAP(m_bmp));

	m_tt.Create(this);
	m_tt.SetMaxTipWidth(0xFFFFFF);

	static int ID[] =
	{
		IDC_EDIT_PWD,
		IDC_EDIT_SELECT_USERNAME,
		IDC_SELECT_CONNECTION,
		IDC_STATIC_DOMAIN,
		IDC_COMBO_DOMAIN,
		IDC_CHK_SAVE,
		IDC_EDIT_NUM_DAYS,
	};
	LPCTSTR about_domain = APL_T("Для авторизации в домене выберите домен Active Directory из списка или введите имя домена вручную.\r\n Для авторизации средствами PSS оставьте поле пустым");
	static const TCHAR *szTipText[] =
	{
		APL_T("Введите пароль пользователя"),
		APL_T("Введите имя пользователя или выберите из списка предыдущих соединений"),
		APL_T("Выберите подключение к БД"),
		about_domain,
		about_domain,
		APL_T("При установке текущие параметры (имя пользователя, пароль, подключение)\r\n будут сохранены в реестре на указанное количество дней"),
		APL_T("Количество дней, на которые будет сохранен логин-пароль (от 1 до 30)"),
	};

	for(int i = 0; i<sizeof(ID)/sizeof(int); i++)
		m_tt.AddTool(GetDlgItem(ID[i]), szTipText[i]);

	m_logo.SetBitmap(HBITMAP(m_bmp));
	
	m_CtrlOk.SetFlat(FALSE);
	m_CtrlOk.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_CtrlCancel.SetFlat(FALSE);
	m_CtrlCancel.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));

	/* - убрано по просьбе Лобанова. Перевод будет выполняться новым механизмом через CaplTranslate.
	if(m_data->m_lang_england)
	{
		m_StaticUsername.SetWindowText(_T("Username:"));
		m_StaticPassword.SetWindowText(_T("Password:"));
		m_StaticConnection.SetWindowText(_T("Connection:"));
		//m_StaticLicense.SetWindowText("License:");
		m_CtrlTune.SetWindowText(_T("Tune..."));
		SetWindowText(_T("Logon to database"));
		m_CtrlCancel.SetWindowText(_T("Cancel"));
	}*/

	FillListConnect();
	//SetForegroundWindow();

	if(!m_type_license.IsEmpty() && global_process_wm_paint)
	{
		CString str;
		GetWindowText(str);
		str += APL_T(" [Тип лицензии: ");
		if(m_type_license == SPEC_LIC_TYPE)
			str += SPEC_LIC_MESS;
		else
			str += m_type_license;
		str += _T("]");
		SetWindowText(str);

		m_StaticLicenseAnnotation.SetWindowText(_T("")); // может, выводить сюда тип лицензии?
//		m_StaticLicenseAnnotation.SetWindowText(str);
	}
	else
	{
		m_StaticLicenseAnnotation.SetWindowText(_T("")); // может, выводить сюда тип лицензии?
	}

	if(m_data->m_AplTransport->m_need_relogin)
	{
		SetWindowText(APL_T("Повторная авторизация в БД"));
		m_CtrlEditSelectUsername.EnableWindow(FALSE);
		m_SelectConnection.EnableWindow(FALSE);
		m_CmbDomain.EnableWindow(FALSE);
		m_CtrlTune.EnableWindow(FALSE);
		m_CtrlSaveLoginData.EnableWindow(FALSE);
		m_CtrlNumDays.EnableWindow(FALSE);
	}
	if(m_sOsDomain.IsEmpty())
	{
		m_CtrlIsDomain.EnableWindow(FALSE);
	}
	else
	{
		m_CtrlIsDomain.EnableWindow(TRUE);
		// Раскомментарить, если надо, чтобы при запуске в домене автоматом утанавливалась галочка "под доменным пользователем"
// 		m_CtrlIsDomain.SetCheck(TRUE);
// 		m_bIsCurrDomainUser = true;
		ChangeUserControls();
	}

	SetKeyboardLayuotInfo();
	SetTimer(TIMER_ID_CONST,TIMER_TIME_CONST,0);

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

BOOL CDlgLogin::PreTranslateMessage(MSG* pMsg) 
{
	if(pMsg != 0)
	{
		if(pMsg->message==WM_INPUTLANGCHANGEREQUEST)
		{
			SetTimer(TIMER_ID_FAST,TIMER_TIME_FAST,0);
		}

		if(pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST)
		{
			m_tt.RelayEvent(pMsg);
		}

	}	
	return CaplTranslateDialog::PreTranslateMessage(pMsg);
}


void CDlgLogin::SetKeyboardLayuotInfo()
{
	TCHAR str[10]; 
	CString cstr;
	GetLocaleInfo( (LCID) MAKELCID(GetKeyboardLayout(NULL),SORT_DEFAULT),LOCALE_SISO639LANGNAME, str, 10);
	cstr = _T(" ");
	cstr += str;
	cstr += _T(" ");
	cstr.MakeUpper();
	m_KeyboardLayout.SetWindowText(cstr);
}


void CDlgLogin::FillListConnect()
{
	int i = 0;
	CString str,win_uname;

	m_CtrlEditSelectUsername.ResetContent();
	m_CmbDomain.ResetContent();

	if(m_bIsCurrDomainUser)
	{
		//CString sFullname = m_sOsUser + _T("@") + m_sOsDomain;
		m_CtrlEditSelectUsername.AddString(m_sOsUser);
		m_CmbDomain.AddString(m_sOsDomain);
	}
	else
	{
		if(m_Username.GetLength()>0)
			m_CtrlEditSelectUsername.AddString(m_Username);

		// Получаем текущий домен и вставить его в комбобокс
		// #ifndef _DEBUG 
		// 	m_CmbDomain.EnableWindow(FALSE);
		// #endif
		CString curr_domain;
		CaplLDAP::GetCurrentWindowsDomainName(curr_domain);
		bool dom_empty = false;
		bool dom_curr = false;

		if(m_data != 0)
		{
			for(int i = 0;i<m_data->m_reg_domain_list.GetSize();i++)
			{
				str=m_data->m_reg_domain_list.GetAt(i);
				m_CmbDomain.AddString(str);

				if(str== _T(""))dom_empty = true;
				else if(str==curr_domain)dom_curr = true;
			}		
		}
		if(!dom_empty)m_CmbDomain.AddString(_T(""));

		if(curr_domain!= _T(""))
		{
			if(!dom_curr)m_CmbDomain.AddString(curr_domain);
			CaplLDAP::GetCurrentWindowsUser(win_uname);
		}

		if(m_data != 0)
		{
			bool not_wun = true;
			if(m_data->m_reg_user_list.GetSize()== 0)
			{
				m_data->m_reg_user_list.Add(_T("Administrator"));
			}
			for(int i = 0;i<m_data->m_reg_user_list.GetSize();i++)
			{
				str=m_data->m_reg_user_list.GetAt(i);
				if(str!=m_Username)
				{
					m_CtrlEditSelectUsername.AddString(str);
				}
				if(str==win_uname)not_wun = false;
			}
			if(win_uname!= _T("") && not_wun)
			{
				m_CtrlEditSelectUsername.AddString(win_uname);
			}
		}

	}
	m_CmbDomain.SetCurSel(0);
	m_CtrlEditSelectUsername.SetCurSel(0);

	if(m_data->m_SingleAlias != _T(""))
	{
		m_cur_name=m_data->m_SingleAlias;
		m_SelectConnection.EnableWindow(FALSE);
		m_CtrlTune.EnableWindow(FALSE);
	}
	m_data->FillConnectionList(m_SelectConnection,m_cur_name,m_cur_select_connection);

}


void CDlgLogin::OnTune() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	int cur_select_connection = m_data->NET_TuningConnections(m_cur_select_connection);

	if(-2==cur_select_connection)
	{
		m_bExitAfterClose=true;
		return EndDialog(FALSE);
	}

	if(cur_select_connection!=-1)m_cur_select_connection = cur_select_connection;
	// ищем активное подключение в новом порядке баз
	FillListConnect();
	OnSelchangeSelectConnection();
	UpdateData(FALSE);

}

void CDlgLogin::OnOK() 
{
	// TODO: Add extra validation here
	bool flag = true;
	UpdateData(TRUE);

	m_cur_select_connection=m_SelectConnection.GetCurSel();
	m_CtrlEditSelectUsername.GetWindowText(m_Username);

	if(m_cur_select_connection==-1)
	{
		AfxMessageBox( APL_T("Поле \"Имя подключения\" не должно быть пустым"),MB_ICONERROR);
		//dlg.m_cur_select_connection=num_base;
		return;
	}

	if(!m_bIsCurrDomainUser)
	{
		if(m_Username== _T(""))
		{
			AfxMessageBox( APL_T("Поле \"Имя пользователя\" не должно быть пустым"),MB_ICONERROR);
			return;
		}
		/* пароль может быть пустым
		else if(dlg.m_Pwd== _T("")){
		MessageBox(m_hwnd,"Поле ""Пароль"" не должно быть пустым","Ошибка ввода",MB_ICONERROR);
		dlg.m_Pwd=pwd;
		continue;
		}*/

		if(m_Domain != _T("") && m_Pwd == _T(""))
		{
			AfxMessageBox( APL_T("Для авторизации в домене требуется ввести пароль"),MB_ICONERROR);
			return;
		}

		if(m_data != 0)
		{
			m_data->AppendString2List(m_data->m_reg_user_list,m_Username);
			m_data->AppendString2List(m_data->m_reg_domain_list,m_Domain);
		}
	}
/*
	int cur_sel_lic=m_SelectTypeLicense.GetCurSel();
	if(cur_sel_lic!=-1)
	{
		m_type_license=m_SelectTypeLicense.GetItemData(cur_sel_lic);
	}
*/	
	CaplTranslateDialog::OnOK();
}


void CDlgLogin::OnSelchangeSelectConnection() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	int num=-1,i = 0;
	CString str;
	m_cur_select_connection=m_SelectConnection.GetCurSel();
	CConnectInfo *cif=m_data->m_list_connection.GetAt(m_cur_select_connection);
	if(cif != 0)
	{
		if(cif->def_user_name != _T(""))
		{
			//m_Username=cif->def_user_name;
			// в списке последних подключенных ищем, нет ли такого
			for(i = 0;i<m_CtrlEditSelectUsername.GetCount();i++)
			{
				m_CtrlEditSelectUsername.GetLBText(i,str);
				if(str==cif->def_user_name)
				{
					num=i;break;
				}
			}
			if(num==-1)
			{
				num=m_CtrlEditSelectUsername.AddString(cif->def_user_name);
			}
			m_CtrlEditSelectUsername.SetCurSel(num);
		}
	}
	UpdateData(FALSE);
	
}

bool CDlgLogin::MoveWnd(CWnd& wnd,int dx,int dy)
{
	CRect rect;
	wnd.GetWindowRect(rect);
	ScreenToClient(&rect);
	rect.top+=dy;
	rect.bottom+=dy;
	rect.left+=dx;
	rect.right+=dx;
	wnd.MoveWindow(rect);
	return true;
}


void CDlgLogin::OnStnClickedStaticUsername()
{
	// TODO: Add your control notification handler code here
	short state=GetKeyState(VK_MENU);
	if((state & 0xff00) != 0)
	{
		//m_Username="Administrator";
		//UpdateData(FALSE);
		m_CtrlEditSelectUsername.SetWindowText(_T("Administrator"));
	}
}



HBRUSH CDlgLogin::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CaplTranslateDialog::OnCtlColor(pDC, pWnd, nCtlColor);

	if(pWnd->GetDlgCtrlID() == IDC_STATIC_KEYBOARD_LAYOUT)
	{
		//pDC->SetBkColor(RGB(0,0,0x7F));
		//pDC->SetTextColor(RGB(0xFF,0xFF,0xFF));
		pDC->SetBkColor(GetSysColor(COLOR_HIGHLIGHT));
		pDC->SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT));
	}
	if(pWnd->GetDlgCtrlID() == IDC_STATIC_LICENSE__ANNOTATION)
	{
		//pDC->SetBkColor(RGB(0,0,0x7F));
		//pDC->SetTextColor(RGB(0xFF,0xFF,0xFF));
		pDC->SetTextColor(RGB(0xA0,0xA0,0xA0));
	}

	// TODO:  Change any attributes of the DC here

	// TODO:  Return a different brush if the default is not desired
	return hbr;
}

void CDlgLogin::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default
	if(nIDEvent==TIMER_ID_FAST || nIDEvent==TIMER_ID_CONST)
	{
		SetKeyboardLayuotInfo();
		KillTimer(TIMER_TIME_FAST);
	}

	CaplTranslateDialog::OnTimer(nIDEvent);
}



void CDlgLogin::OnCbnSelchangeEditSelectUsername()
{
	// TODO: Add your control notification handler code here
	CheckClearFlagSave();
}

void CDlgLogin::OnCbnEditchangeEditSelectUsername()
{
	// TODO: Add your control notification handler code here
	CheckClearFlagSave();
}

void CDlgLogin::CheckClearFlagSave()
{
	if(m_started_uname)
	{
		m_started_uname = false;
		m_IsSaveLoginData = false;
		UpdateData(FALSE);
	}
}
void CDlgLogin::OnBnClickedChk()
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	ChangeUserControls();
}

void CDlgLogin::ChangeUserControls()
{
	BOOL state = m_bIsCurrDomainUser?FALSE:TRUE;

	m_CtrlEditSelectUsername.EnableWindow(state);
	//m_SelectTypeLicense.EnableWindow(state);
	m_CmbDomain.EnableWindow(state);
	m_CtrlEditPwd.EnableWindow(state);
	m_CtrlSaveLoginData.EnableWindow(state);
	m_CtrlNumDays.EnableWindow(state);

	FillListConnect();
}
