// OptionsWorkDlg.cpp : implementation file
//

#include "stdafx.h"
#include "psm.h"
#include "OptionsWorkDlg.h"
#include "aplDocTreeItem.h"
#include "TreeProductItem.h"
#include "aplTreeApprovalItem.h"
#include "aplFolderTreeItem.h"
#include "PSMDoc.h"
#include "resource.h"

#include <aplStepManager.h>

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

/////////////////////////////////////////////////////////////////////////////
// COptionsWorkDlg dialog


COptionsWorkDlg::COptionsWorkDlg(CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(COptionsWorkDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(COptionsWorkDlg)
	m_mesTime = 0;
	m_work_folder = _T("");

	m_show_select_app_dlg = FALSE;
	m_auto_change_wf_state = FALSE;
	m_create_assoc_folder_doc = FALSE;
	m_taskTime = 0;
	m_auto_sign = FALSE;
	//}}AFX_DATA_INIT
	m_doc=0;
	m_taskDelive = TRUE;
	m_mesDelive = TRUE;
	m_NotifyWithPersonalMonitor = TRUE;

	
}

void COptionsWorkDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(COptionsWorkDlg)
	DDX_Control(pDX, IDC_AUTO_CHANGE_WF_STATE, m_auto_change_wf_state_ctrl);
	DDX_Control(pDX, IDC_AUTO_SIGN, m_auto_sign_ctrl);
	DDX_Control(pDX, IDC_AUTO_DELIVE_TASK_RB2, m_taskCheckCtrl);
	DDX_Control(pDX, IDC_AUTO_DELIVE_RB, m_mesCheckCtrl);
	DDX_Control(pDX, IDC_AUTO_DELIVE_TASK_TIME, m_taskTimeCtrl);
	DDX_Control(pDX, IDC_AUTO_DELIVE_TASK_TIME_SET, m_taskTimeSet);
	DDX_Control(pDX, IDC_SEL_CONFIGURATION, m_sel_conf);
	DDX_Control(pDX, IDC_SHOW_SELECT_APP_DLG, m_show_select_app_dlg_ctrl);
	DDX_Text(pDX, IDC_AUTO_DELIVE_TIME, m_mesTime);
	DDX_Check(pDX, IDC_AUTO_DELIVE_RB, m_mesDelive);
	DDX_Control(pDX, IDC_AUTO_DELIVE_TIME_SET, m_mesTimeSet);
	DDX_Control(pDX, IDC_AUTO_DELIVE_TIME, m_mesTimeCtrl);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_SEL_CONTEXT, m_sel_context);
	DDX_Text(pDX, IDC_WORK_FOLDER, m_work_folder);
	DDX_Check(pDX, IDC_SHOW_SELECT_APP_DLG, m_show_select_app_dlg);
	DDX_Check(pDX, IDC_AUTO_CHANGE_WF_STATE, m_auto_change_wf_state);
	DDX_Check(pDX, IDC_CREATE_ASS_DOC_FOLDER, m_create_assoc_folder_doc);
	DDX_Check(pDX, IDC_AUTO_DELIVE_TASK_RB2, m_taskDelive);
	DDX_Check(pDX, IDC_NOTIFY_WITH_PERSMONITOR, m_NotifyWithPersonalMonitor);
	DDX_Text(pDX, IDC_AUTO_DELIVE_TASK_TIME, m_taskTime);
	DDX_Check(pDX, IDC_AUTO_SIGN, m_auto_sign);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_USE_APL_MARKUP, m_useAplMarkup);
	DDX_Control(pDX, IDC_WORK_FOLDER, m_work_folder_ctrl);
	DDX_Control(pDX, IDC_NOTIFY_WITH_PERSMONITOR, m_UsePesonalMonitorCtrl);
	DDX_Control(pDX, IDC_SEL_LOG_LODE, m_SelLogModeCtrl);
}


BEGIN_MESSAGE_MAP(COptionsWorkDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(COptionsWorkDlg)
	ON_WM_CANCELMODE()
	ON_NOTIFY(UDN_DELTAPOS, IDC_AUTO_DELIVE_TIME_SET, OnDeltaposAutoDeliveTimeSet)
	ON_EN_CHANGE(IDC_AUTO_DELIVE_TIME, OnChangeAutoDeliveTime)
	ON_BN_CLICKED(IDC_AUTO_DELIVE_RB, OnAutoDeliveRb)
	ON_EN_CHANGE(IDC_AUTO_DELIVE_TASK_TIME, OnChangeAutoDeliveTaskTime)
	ON_NOTIFY(UDN_DELTAPOS, IDC_AUTO_DELIVE_TIME_TASK_SET, OnDeltaposAutoDeliveTimeTaskSet)
	ON_BN_CLICKED(IDC_AUTO_DELIVE_TASK_RB2, OnAutoDeliveTaskRb2)
	ON_NOTIFY(UDN_DELTAPOS, IDC_AUTO_DELIVE_TASK_TIME_SET, OnDeltaposAutoDeliveTimeTaskSet)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_SEL_WORK_FOLDER, &COptionsWorkDlg::OnBnClickedSelWorkFolder)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// COptionsWorkDlg message handlers

BOOL COptionsWorkDlg::OnInitDialog() 
{
	if(!m_doc->m_api.m_data.IsConnected())
	{
		AfxMessageBox( APL_T("Соединение не установлено!"), MB_OK|MB_ICONERROR);
		EndDialog(IDCANCEL);
	}


	m_show_select_app_dlg=CaplDocTreeItem::m_bShowSelectAppDlg;
	m_work_folder=CaplDocTreeItem::m_EditPath;

	int opt=0;
	m_doc->m_api.m_options_mgr.GetOptionValueBN( APL_NO_T("Настройка документов\\Запретить ассоциацию с папкой"),opt,0);
	if(1==opt)
	{
		m_create_assoc_folder_doc=false;
		CWnd *wnd=GetDlgItem(IDC_CREATE_ASS_DOC_FOLDER);
		if(wnd)	wnd->EnableWindow(FALSE);
	}
	else 	m_create_assoc_folder_doc = CaplFolderManager::m_create_assoc_folder_doc;

	if(!m_doc->m_bIsAdmin)
	{
		if(GetDlgItem(IDC_CHEK_UNIK_PRD_BY_ID_AND_NAME))
			GetDlgItem(IDC_CHEK_UNIK_PRD_BY_ID_AND_NAME)->EnableWindow(FALSE);
	}


	CaplTranslateDialog::OnInitDialog();
	
	m_auto_sign= (BOOL)m_doc->m_api.m_options_mgr.GetIntOptionValueBN( APL_NO_T("Настройка документов\\Всегда подписывать документы ЭЦП"), 0);
	if(!m_doc->m_bIsAdmin)
	{
		m_auto_sign_ctrl.EnableWindow(FALSE);
		m_auto_change_wf_state_ctrl.EnableWindow(FALSE);
	}

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

	// TODO: Add extra initialization here

	int i=0;
	m_SelLogModeCtrl.ResetContent();
	i=m_SelLogModeCtrl.AddString(APL_T("0 - Ничего не выводить"));
	m_SelLogModeCtrl.SetItemData(i,0);
	i=m_SelLogModeCtrl.AddString(APL_T("1 - Только ошибки"));
	m_SelLogModeCtrl.SetItemData(i,1);
	i=m_SelLogModeCtrl.AddString(APL_T("2 - Ошибки и предупреждения"));
	m_SelLogModeCtrl.SetItemData(i,2);
	i=m_SelLogModeCtrl.AddString(APL_T("3 - Служебную интформацию"));
	m_SelLogModeCtrl.SetItemData(i,3);
	i=m_SelLogModeCtrl.AddString(APL_T("4 - Подробную информацию"));
	m_SelLogModeCtrl.SetItemData(i,4);
	i=m_SelLogModeCtrl.AddString(APL_T("5 - Отладочную информаию"));
	m_SelLogModeCtrl.SetItemData(i,5);
	i=m_SelLogModeCtrl.AddString(APL_T("6 - Параноидальный режим"));
	m_SelLogModeCtrl.SetItemData(i,6);

	for(i=0; i<m_SelLogModeCtrl.GetCount(); i++)
	{
		if(CaplNetStepData::g_CurLogMode==m_SelLogModeCtrl.GetItemData(i))
		{
			m_SelLogModeCtrl.SetCurSel(i);
			break;
		}
	}



	
//	HWND hwnd= ::GetWindow(m_auto_delive_time_ctrl.m_hWnd, GW_OWNER);
	m_buddyMesWnd= FromHandle(m_mesTimeCtrl.m_hWnd);
	m_mesTimeSet.SetBuddy(m_buddyMesWnd);
	SetTimers();
	m_mesTimeSet.SetRange32(1, iMidTime);
	m_mesTimeSet.SetPos(m_mesTime);
	
	if(!m_mesDelive)
	{
		m_mesTimeCtrl.EnableWindow(FALSE);
		m_mesTimeSet.EnableWindow(FALSE);
	}
	
	m_buddyTaskWnd= FromHandle(m_taskTimeCtrl.m_hWnd);
	m_taskTimeSet.SetBuddy(m_buddyTaskWnd);
	m_taskTimeSet.SetRange32(1, iMaxTime);
	m_taskTimeSet.SetPos(m_taskTime);
	if(!m_taskDelive)
	{
		m_taskTimeCtrl.EnableWindow(FALSE);
		m_taskTimeSet.EnableWindow(FALSE);
	}

	int j;
	if(m_doc==0) m_sel_context.EnableWindow(FALSE);
	else
	{
		// Заполнение контекстов
		if(m_doc_data.IsConnected())
		{
			CString buf;
			aplExtent ext_contexts;
			m_doc_data.GetEntityExtent(m_doc->m_api.m_prd_mgr.e_pd_context,ext_contexts);
			for(i=0;i<ext_contexts.Size;i++)
			{
				m_doc_data.GetAttr(ext_contexts[i],m_doc->m_api.m_prd_mgr.a_pd_context_name,buf);
				j=m_sel_context.AddString(buf);
				m_sel_context.SetItemData(j,(long)ext_contexts[i]);
			}
		}
		j=m_sel_context.AddString( APL_T("Все контексты"));
		m_sel_context.SetItemData(j,0);
		m_sel_context.SetCurSel(j);

		if(m_doc->m_cur_context!=0)
		{
			for(i=0;i<m_sel_context.GetCount();i++)
			{
				if((DWORD)(m_doc->m_cur_context)==m_sel_context.GetItemData(i)) 
				{
					m_sel_context.SetCurSel(i);
					break;
				}
			}
		}
	}

	InitConfigurations();
	UpdateData(FALSE);

	m_useAplMarkup.SetCheck(CaplDocManager::m_bUseAplMarkView);

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

void COptionsWorkDlg::OnOK() 
{
	UpdateData(TRUE);
	CaplMaskedEdit medt;

	if(m_doc==0) return;

	if(m_work_folder.GetLength()>0)
	{
		if(m_work_folder[m_work_folder.GetLength()-1]!=_T('\\')) m_work_folder+=_T("\\");
	}
	CaplDocTreeItem::m_EditPath=m_work_folder;
//	CProductDlg::m_mask=m_prd_id_mask;
	CaplFolderManager::m_create_assoc_folder_doc = m_create_assoc_folder_doc;

	if(m_show_select_app_dlg)
		CaplDocTreeItem::m_bShowSelectAppDlg=true;
	else CaplDocTreeItem::m_bShowSelectAppDlg=false;
	
	if(m_doc->m_bIsAdmin)
		m_doc->m_api.m_options_mgr.CreateOption( APL_NO_T("Настройка документов\\Всегда подписывать документы ЭЦП"), m_auto_sign);
	

//	SetTimers();
	if(m_mesTime<1)
		m_mesTime= 1;
	if(m_mesTime>iMidTime)
		m_mesTime=iMidTime;
	
	if(m_taskTime<1)
		m_taskTime = 1;
	if(m_taskTime>iMaxTime)
		m_taskTime= iMaxTime;

	m_doc->m_cur_context=(CaplInstance *)m_sel_context.GetItemData(m_sel_context.GetCurSel());

	int confIndex = m_sel_conf.GetCurSel();
	if(-1 != confIndex)
	{
		CaplInstance *pConfiguration = reinterpret_cast<CaplInstance*>(m_sel_conf.GetItemData(confIndex));
		m_doc->SetCurrentConfiguration(pConfiguration);
	}

	BOOL b=m_useAplMarkup.GetCheck();

	if(CaplDocManager::m_bUseAplMarkView!=b)
	{
		CaplDocManager::m_bUseAplMarkView=b;
		CaplStepManager::SaveGlobalParams();
	}

	CaplDocManager::m_bUseAplMarkView=m_useAplMarkup.GetCheck();

	int i=m_SelLogModeCtrl.GetCurSel();
	if(i>=0)
	{
		CaplNetStepData::g_CurLogMode=(aplLogMode)m_SelLogModeCtrl.GetItemData(i);
		CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
		if(0!=app) app->WriteProfileInt(_T("options"), _T("g_CurLogMode"), CaplNetStepData::g_CurLogMode);
	}


	CaplTranslateDialog::OnOK();
}

void COptionsWorkDlg::OnCancelMode() 
{
	CaplTranslateDialog::OnCancelMode();
	
	// TODO: Add extra initialization here
	UpdateData(FALSE);
}

void COptionsWorkDlg::OnDeltaposAutoDeliveTimeSet(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
	// TODO: Add your control notification handler code here
	m_mesTime= pNMUpDown->iPos;
	UpdateData(FALSE);
	*pResult = 0;
}

void COptionsWorkDlg::OnDeltaposAutoDeliveTimeTaskSet(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
	// TODO: Add your control notification handler code here
	m_taskTime= pNMUpDown->iPos;
	UpdateData(FALSE);	
	*pResult = 0;
}

void COptionsWorkDlg::OnChangeAutoDeliveTime() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData();	
//	SetTimers();
	if(m_mesTime<1)
	{
		m_mesTime= 1;
		m_mesTimeCtrl.SetSel(-1, -1);
	}
	if(m_mesTime>iMidTime)
	{
		m_mesTime= iMidTime;
		m_mesTimeCtrl.SetSel(-1, -1);
	}
	m_mesTimeSet.SetPos(m_mesTime);
	UpdateData(FALSE);
}

void COptionsWorkDlg::OnChangeAutoDeliveTaskTime() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData();	
//	SetTimers();
	if(m_taskTime<1)
	{
		m_taskTime= 1;
		m_taskTimeCtrl.SetSel(0, -1);
	}
	if(m_taskTime>iMaxTime)
	{
		m_taskTime= iMaxTime;
		m_taskTimeCtrl.SetSel(0, 1);
	}
	m_taskTimeSet.SetPos(m_taskTime);	
	UpdateData(FALSE);
}

void COptionsWorkDlg::OnAutoDeliveRb() 
{
	UpdateData();	
	if(!m_mesDelive)
	{
		m_mesTimeCtrl.EnableWindow(FALSE);
		m_mesTimeSet.EnableWindow(FALSE);
	}
	else
	{
		m_mesTimeCtrl.EnableWindow();
		m_mesTimeSet.EnableWindow();
	}
}

void COptionsWorkDlg::OnAutoDeliveTaskRb2() 
{
	UpdateData();	
	if(!m_taskDelive)
	{
		m_taskTimeCtrl.EnableWindow(FALSE);
		m_taskTimeSet.EnableWindow(FALSE);
	}
	else
	{
		m_taskTimeCtrl.EnableWindow();
		m_taskTimeSet.EnableWindow();
	}	
}

void COptionsWorkDlg::SetTimers()
{
	CString sMidTime= APL_NO_T("Автоматическая проверка новых сообщений, заданий, процессов, напоминаний\\Интервал проверки новых");
	CString sMaxTime= APL_NO_T("Автоматическая проверка новых сообщений, заданий, процессов, напоминаний\\Интервал напоминания о наличии невыполненных");
	
	CString sCanEditTime= APL_NO_T("Автоматическая проверка новых сообщений, заданий, процессов, напоминаний\\Возможность отключения монитора");
	
	CString name, par_name;
	CString sMinTimeVal;
	int iMyMid=0;
	int iMyMax=0;
	int iCanEdit=1;

	m_doc->m_api.m_options_mgr.GetOptionValueBN(sMidTime, iMyMid, 5);
	m_doc->m_api.m_options_mgr.GetOptionValueBN(sMaxTime, iMyMax, 30);
	m_doc->m_api.m_options_mgr.GetOptionValueBN(sCanEditTime, iCanEdit, 1);

	iMinTime = 1;
	if(iMyMid<=0) iMyMid= 5;
	if(iMyMax<=0) iMyMax= 30;
	
	m_mesCheckCtrl.EnableWindow(iCanEdit);
	m_taskCheckCtrl.EnableWindow(iCanEdit);
		
	if(iMyMid<iMyMax)
	{
		iMaxTime = iMyMax;
		iMidTime = iMyMid;
	}
	else
	{
		iMaxTime = iMyMid;
		iMidTime = iMyMax;
	}

//	if(0!=iMyMid)
//		iMidTime = (UINT)iMyMid;
//	else
//		iMidTime = 5;
//	
//	if(0!=iMyMax)
//		iMaxTime = (UINT)iMyMax;
//	else
//		iMaxTime = 30;
//
//	if(iMaxTime>30)
//		iMaxTime=30;
//	
//	if(iMidTime>5)
//		iMidTime=5;
//	
//	if(iMaxTime<iMidTime)
//	{
//		iMaxTime=30;
//		iMidTime=5;
//	}
}

void COptionsWorkDlg::InitConfigurations()
{
	void (*funcFillComboWithConfigurations)(CaplAPI*, CComboBox&, CaplInstance*) = NULL;
	if(m_doc->m_hConfigMgrLib != NULL)
	{
		(FARPROC&)funcFillComboWithConfigurations = ::GetProcAddress(m_doc->m_hConfigMgrLib, "add_FillComboWithConfigurations");	
		if(funcFillComboWithConfigurations)
			funcFillComboWithConfigurations(&m_doc->m_api, m_sel_conf, m_doc->GetCurrentConfiguration());
	}		
}

void COptionsWorkDlg::OnBnClickedSelWorkFolder()
{
	CString sPath;
	m_work_folder_ctrl.GetWindowText(sPath);
	CaplSelectFolderDialog dlg(FALSE, sPath, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, NULL, NULL);
	if(dlg.DoModal()!=IDOK) return;
	sPath = dlg.GetSelectedPath();
	m_work_folder_ctrl.SetWindowText(sPath);
}
