// AlertPropertiesDlg.cpp : implementation file
//

#include "stdafx.h"
#include "AlertPropertiesDlg.h"
#include "apl_api.h"
#include "ShowAlertsDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAlertPropertiesDlg dialog


CAlertPropertiesDlg::CAlertPropertiesDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CAlertPropertiesDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAlertPropertiesDlg)
	//}}AFX_DATA_INIT
	m_alert=0;
	m_api=0;
	m_mode=APL_MODE_RECIEVED;
	m_read_only=false;
	m_author=0;
	m_recipient=0;
	m_cur_person=0;
	m_object=0;

	m_active_state=0;
	m_completed_state=0;
}


void CAlertPropertiesDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAlertPropertiesDlg)
	DDX_Control(pDX, IDC_CLEAR_OBJECT, m_clear_object_btn);
	DDX_Control(pDX, IDC_SELECT_OBJECT_BTN, m_select_object_btn);
	DDX_Control(pDX, IDC_OBJECT, m_object_ctrl);
	DDX_Control(pDX, IDC_SELECT_RECIPIENT_BTN, m_select_recipient_btn);
	DDX_Control(pDX, IDC_SELECT_AUTHOR_BTN, m_select_author_btn);
	DDX_Control(pDX, IDC_RECIPIENT, m_recipient_ctrl);
	DDX_Control(pDX, IDC_AUTHOR, m_author_ctrl);
	DDX_Control(pDX, IDC_STATE, m_state_ctrl);
	DDX_Control(pDX, IDC_STATE_TEXT, m_state_text);
	DDX_Control(pDX, IDC_NOTIFY, m_notify_check);
	DDX_Control(pDX, IDC_DELETE_COMPLETED, m_delete_completed_check);
	DDX_Control(pDX, IDC_START_ALERT_TO, m_start_alert_to_btn);
	DDX_Control(pDX, IDC_START_ALERT_FROM, m_start_alert_from_btn);
	DDX_Control(pDX, IDC_START_ALERT_MINUTS, m_start_alert_minuts_ctrl);
	DDX_Control(pDX, IDC_START_ALERT_HOURS, m_start_alert_hours_ctrl);
	DDX_Control(pDX, IDC_START_ALERT_DAYS, m_start_alert_days_ctrl);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_SPAN_MINUTS, m_span_minuts_ctrl);
	DDX_Control(pDX, IDC_SPAN_HOURS, m_span_hours_ctrl);
	DDX_Control(pDX, IDC_PERF_TIME, m_perf_time_ctrl);
	DDX_Control(pDX, IDC_PERF_DATE, m_perf_date_ctrl);
	DDX_Control(pDX, IDC_NEXT_TIME, m_next_time_ctrl);
	DDX_Control(pDX, IDC_NEXT_DATE, m_next_date_ctrl);
	DDX_Control(pDX, IDC_ALERT_TEXT, m_alert_text_ctrl);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CAlertPropertiesDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CAlertPropertiesDlg)
	ON_BN_CLICKED(IDC_START_ALERT_TO, OnStartAlertTo)
	ON_BN_CLICKED(IDC_START_ALERT_FROM, OnStartAlertFrom)
	ON_BN_CLICKED(IDC_SELECT_AUTHOR_BTN, OnSelectAuthorBtn)
	ON_BN_CLICKED(IDC_SELECT_RECIPIENT_BTN, OnSelectRecipientBtn)
	ON_BN_CLICKED(IDC_SELECT_OBJECT_BTN, OnSelectObjectBtn)
	ON_BN_CLICKED(IDC_CLEAR_OBJECT, OnClearObject)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAlertPropertiesDlg message handlers

BOOL CAlertPropertiesDlg::OnInitDialog() 
{
	CaplResizableDialog::OnInitDialog();
	if(m_api==NULL)
	{
		EndDialog(0);
		return FALSE;
	}

	// предотвращаем потерю модальности после диалога с бочками из aplSocketTransport
	CORRECT_LOOSE_MODAL_ON_CLASS(&(m_api->m_data));
	
	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   
	
	m_clear_object_btn.SetTooltipText( APL_T("Удалить связь"));
	m_clear_object_btn.SetIcon(GetAplTableIco(APL_TABLE_DEL));
	m_clear_object_btn.SetFlat(FALSE);
	
	m_ok_btn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_ok_btn.SetFlat(FALSE);
	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);

	m_start_alert_to_btn.SetCheck(1);
	m_start_alert_days_ctrl.SetWindowText(_T("1"));
	m_start_alert_hours_ctrl.SetWindowText(_T("0"));
	m_start_alert_minuts_ctrl.SetWindowText(_T("0"));
	m_span_hours_ctrl.SetWindowText(_T("0"));
	m_span_minuts_ctrl.SetWindowText(_T("30"));

	m_active_state=m_state_ctrl.AddString(CaplTranslate::Translate(m_api->m_message_mgr.m_alert_state_active));
	 m_completed_state=m_state_ctrl.AddString(CaplTranslate::Translate(m_api->m_message_mgr.m_alert_state_completed));

	bool notify,delete_completed;
	m_cur_person=m_api->m_message_mgr.GetCurrentPerson();
	CString buf=_T("");
	if(m_alert)
	{
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_author,m_author);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_person,m_recipient);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_item,m_object);
		if(m_object) m_api->GetItemName(m_object,buf);
		m_object_ctrl.SetWindowText(buf);

		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_text,buf);
		m_alert_text_ctrl.SetWindowText(buf);

		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_state,buf);
		if(buf==_T("")) buf=CString(m_api->m_message_mgr.m_alert_state_active);
		if(buf==CString(m_api->m_message_mgr.m_alert_state_active)) 
			m_state_ctrl.SetCurSel(m_active_state);
		else 
			m_state_ctrl.SetCurSel(m_completed_state);

		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_delete_completed,delete_completed);
		if(delete_completed) m_delete_completed_check.SetCheck(1);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_notify_author,notify);
		if(notify) m_notify_check.SetCheck(1);

		COleDateTime dt;
		//дата события
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_date,buf);
		if(buf!=_T(""))	aplString2Date(buf,dt);
		else dt = COleDateTime::GetCurrentTime();
		m_perf_date_ctrl.SetTime(dt);	
		m_perf_time_ctrl.SetTime(dt);
		//следующая дата напоминания 
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_next_date,buf);
		if(buf!=_T(""))	
		{
			aplString2Date(buf,dt);
			if(dt.GetStatus()==COleDateTime::valid) 
			{
				m_next_date_ctrl.SetTime(dt);	
				m_next_time_ctrl.SetTime(dt);
				m_start_alert_from_btn.SetCheck(1);
				OnStartAlertFrom();
			}
		}

		//интервал напоминания
		double span=0;
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_span,span);
		COleDateTimeSpan dt_span=span;
		if(dt_span.GetStatus()==COleDateTimeSpan::valid)
		{
			int span_hours=dt_span.GetHours();
			buf.Format(_T("%d"),span_hours);
			m_span_hours_ctrl.SetWindowText(buf);
			int span_minuts=dt_span.GetMinutes();
			buf.Format(_T("%d"),span_minuts);
			m_span_minuts_ctrl.SetWindowText(buf);
		}
	
	}
	else
	{
		m_state_ctrl.SetCurSel(0);
		m_state_ctrl.EnableWindow(false);
		if(!m_author) m_author=m_cur_person;
		if(m_author==m_recipient)
		{
			m_delete_completed_check.SetCheck(1);
		}
		else
		{
			m_notify_check.SetCheck(1);
		}
	}
	if(m_author) 
	{
		m_api->GetItemName(m_author,buf);
		m_author_ctrl.SetWindowText(buf);
	}
	if(m_recipient) 
	{
		m_api->GetItemName(m_recipient,buf);
		m_recipient_ctrl.SetWindowText(buf);
	}
	SetReadOnlyItems();
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CAlertPropertiesDlg::OnStartAlertTo() 
{
	// TODO: Add your control notification handler code here
	m_start_alert_from_btn.SetCheck(0);
	m_next_date_ctrl.EnableWindow(false);
	m_next_time_ctrl.EnableWindow(false);
	m_start_alert_days_ctrl.EnableWindow(true);
	m_start_alert_hours_ctrl.EnableWindow(true);
	m_start_alert_minuts_ctrl.EnableWindow(true);
}

void CAlertPropertiesDlg::OnStartAlertFrom() 
{
	m_start_alert_to_btn.SetCheck(0);
	m_next_date_ctrl.EnableWindow(true);
	m_next_time_ctrl.EnableWindow(true);
	m_start_alert_days_ctrl.EnableWindow(false);
	m_start_alert_hours_ctrl.EnableWindow(false);
	m_start_alert_minuts_ctrl.EnableWindow(false);
	
}

bool CAlertPropertiesDlg::SaveChanges()
{
	if(m_read_only) return true;
	CString alert_text=_T(""),perf_date=_T(""),next_date=_T(""),state=_T(""),buf=_T("");
	COleDateTime perf_dt,next_dt;
	COleDateTime t_time,d_time;
	COleDateTimeSpan dt_span;
	double span=0,old_span;
	CString days,hours,minuts;
	bool delete_completed=false,old_delete_completed;
	bool notify_author=false,old_notify_author;
	CaplInstance *old_recipient=0,*old_author=0,*old_object=0;

	//текст напоминания
	m_alert_text_ctrl.GetWindowText(alert_text);
	if(alert_text==_T("")) {AfxMessageBox( APL_T("Необходимо задать описание напоминания!"));return false;}
	if(!m_recipient) {AfxMessageBox( APL_T("Не задан получатель напоминания!"));return false;}

	//состояние
	// переделано для перевода m_state_ctrl.GetWindowText(state);
	if(m_completed_state==m_state_ctrl.GetCurSel()) state=m_api->m_message_mgr.m_alert_state_completed;
	else state=m_api->m_message_mgr.m_alert_state_active;

	//удалять выполненные или нет
	int check=m_delete_completed_check.GetCheck();
	if(check==1) delete_completed=true;
	//уведомлять или нет автора
	check=m_notify_check.GetCheck();
	if(check==1) notify_author=true;

	//дата события
	m_perf_date_ctrl.GetTime(d_time);	
	m_perf_time_ctrl.GetTime(t_time);
	perf_dt.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),
		t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());
	aplDate2String(perf_dt,perf_date);
	
	//следующая дата напоминания
	COleDateTime cur_dt=COleDateTime::GetCurrentTime();
	int next_date_mode=m_start_alert_to_btn.GetCheck();
	if(next_date_mode==1) //следующая дата отображения высчитывается назад относительно даты события
	{
		m_start_alert_days_ctrl.GetWindowText(days);
		m_start_alert_hours_ctrl.GetWindowText(hours);
		m_start_alert_minuts_ctrl.GetWindowText(minuts);
		COleDateTimeSpan next_date_span;
		next_date_span.SetDateTimeSpan(_atoi(days),_atoi(hours),_atoi(minuts),0);
		next_dt=perf_dt-next_date_span;
	}
	else
	{
		m_next_date_ctrl.GetTime(d_time);	
		m_next_time_ctrl.GetTime(t_time);
		next_dt.SetDateTime(d_time.GetYear(),d_time.GetMonth(),d_time.GetDay(),
			t_time.GetHour(),t_time.GetMinute(),t_time.GetSecond());
	}
	if(next_dt<cur_dt) 
	{
		if(IDNO==AfxMessageBox( APL_T("Дата начала напоминаний < текущего момента времени. Начать напоминать сразу же ?"),MB_YESNO|MB_ICONQUESTION))
			return false;
		next_dt=cur_dt;
	}
	aplDate2String(next_dt,next_date);	

	//интервал напоминания
	m_span_hours_ctrl.GetWindowText(hours);
	m_span_minuts_ctrl.GetWindowText(minuts);
	int span_hours=_atoi(hours);
	int span_minuts=_atoi(minuts);
	dt_span.SetDateTimeSpan(0,span_hours,span_minuts,0);
	double total_minuts=dt_span.GetTotalMinutes();
	if(total_minuts<5)
	{
		AfxMessageBox( APL_T("Интервал напоминаний не может быть меньше 5 минут! \nУстановлен интервал напоминаний равный 5 минутам"));
		total_minuts=5;
	}
	else if(total_minuts>240)
	{
		AfxMessageBox( APL_T("Интервал напоминаний не может быть больше 4 часов! \nУстановлен интервал напоминаний равный 4 часам"));
		total_minuts=240;
	}
	if(m_alert && !m_api->m_message_mgr.IsAdmin())//какой угодно интервал (в границах от 5 до 240) может устанавливать
										   //либо админ, либо автор напоминания
	{
	
		if(m_cur_person!=m_author)
		{
			double old_span,old_minuts;
			m_api->m_data.GetAttr(m_alert, m_api->m_message_mgr.a_alert_span, old_span);
			dt_span=old_span;
			if(dt_span.GetStatus()==COleDateTimeSpan::valid)
			{
				old_minuts=dt_span.GetTotalMinutes();
				if(int(old_minuts)<total_minuts) 
				{
					AfxMessageBox( APL_T("Недостаточно прав для изменения интервала напоминаний в большую сторону! \nИнтервал напоминаний не будет изменен."));
					total_minuts=int(old_minuts);
				}
			}
		}
	}
	dt_span.SetDateTimeSpan(0,0,int(total_minuts),0);
	span=dt_span;

	if(m_alert)
	{
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_text,buf);
		if(buf!=alert_text)	m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_text,alert_text);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_date,buf);
		if(buf!=perf_date) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_date,perf_date);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_next_date,buf);
		if(buf!=next_date) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_next_date,next_date);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_span,old_span);
		if(old_span!=span) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_span,span);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_delete_completed,old_delete_completed);
		if(old_delete_completed!=delete_completed) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_delete_completed,delete_completed);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_notify_author,old_notify_author);
		if(old_notify_author!=notify_author) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_notify_author,notify_author);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_person,old_recipient);
		if(old_recipient!=m_recipient) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_person,m_recipient);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_author,old_author);
		if(old_author!=m_author) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_author,m_author);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_item,old_object);
		if(old_object!=m_object) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_item,m_object);
		m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_state,buf);
		if(buf==_T("")) buf=CString(m_api->m_message_mgr.m_alert_state_active);
		if(buf!=state) 
		{
			if(state==CString(m_api->m_message_mgr.m_alert_state_active)) m_api->m_data.PutAttr(m_alert,m_api->m_message_mgr.a_alert_state,m_api->m_message_mgr.m_alert_state_active);
			else m_api->m_message_mgr.SetAlertState(m_alert,m_api->m_message_mgr.m_alert_state_completed);
		}
		
	}
	else
	{
		m_alert=m_api->m_message_mgr.CreateAlert(m_recipient,m_object,alert_text,0,perf_dt,next_dt,dt_span,_T(""),_T(""),m_author,delete_completed,notify_author);
	}
	return true;

}

void CAlertPropertiesDlg::OnOK() 
{
	// TODO: Add extra validation here

	if(!SaveChanges()) return;
	CaplResizableDialog::OnOK();
}

void CAlertPropertiesDlg::SetReadOnlyItems()
{
	if(!m_cur_person) 
	{
		m_read_only=true;
	}
	else
	{
		if(m_api->m_message_mgr.IsAdmin())
		{
			m_mode=APL_MODE_ADMIN;
		}
		else
		{
			if(m_cur_person==m_author)
			{
				m_mode=APL_MODE_GIVEN;
			}
			else
			{
				if(m_cur_person==m_recipient)
				{
					m_mode=APL_MODE_RECIEVED;
				}
				else
				{
					m_read_only=true;
				}
			}
		}
	}
	CString state=CString(m_api->m_message_mgr.m_alert_state_active);
	if(m_alert) m_api->m_data.GetAttr(m_alert,m_api->m_message_mgr.a_alert_state,state);
	if(state==_T("")) state=CString(m_api->m_message_mgr.m_alert_state_active);
	if(m_read_only || m_mode==APL_MODE_RECIEVED)
	{
		m_alert_text_ctrl.SetReadOnly(true);
		m_perf_date_ctrl.EnableWindow(false);
		m_perf_time_ctrl.EnableWindow(false);
		m_next_date_ctrl.EnableWindow(false);
		m_next_time_ctrl.EnableWindow(false);
		m_start_alert_days_ctrl.EnableWindow(false);
		m_start_alert_hours_ctrl.EnableWindow(false);
		m_start_alert_minuts_ctrl.EnableWindow(false);	
		m_start_alert_days_ctrl.EnableWindow(false);
		m_start_alert_hours_ctrl.EnableWindow(false);
		m_start_alert_minuts_ctrl.EnableWindow(false);
		m_notify_check.EnableWindow(false);
		m_delete_completed_check.EnableWindow(false);
		m_select_author_btn.EnableWindow(false);
		m_select_recipient_btn.EnableWindow(false);
		m_start_alert_to_btn.EnableWindow(false);
		m_start_alert_from_btn.EnableWindow(false);
		m_select_object_btn.EnableWindow(false);
		m_clear_object_btn.EnableWindow(false);
		//if(state=="выполнено") m_state_ctrl.EnableWindow(false);
	}
	if(m_read_only)
	{
		m_span_hours_ctrl.EnableWindow(false);
		m_span_minuts_ctrl.EnableWindow(false);
		m_state_ctrl.EnableWindow(false);
		m_ok_btn.EnableWindow(false);
	}
	if(m_mode!=APL_MODE_ADMIN) m_select_author_btn.EnableWindow(false);
}

void CAlertPropertiesDlg::OnSelectAuthorBtn() 
{
	aplExtent ext;
	
	CaplInstance *inst=m_api->m_appr_mgr.SelectPersonOrOrganization(APL_MODE_SELECT_PERSON, ext,  APL_T("Выбор автора задания"),  APL_T("Выбор сотрудника"));
	if(inst)
	{
		m_author=inst;
		CString buf;
		m_api->GetItemName(m_author,buf);
		m_author_ctrl.SetWindowText(buf);
	}

}

void CAlertPropertiesDlg::OnSelectRecipientBtn() 
{
	// TODO: Add your control notification handler code here
	aplExtent ext;
	CaplInstance *inst=m_api->m_appr_mgr.SelectPersonOrOrganization(APL_MODE_SELECT_PERSON|APL_MODE_SELECT_OFFICIAL, ext,  APL_T("Выбор получателя задания"),  APL_T("Выбор сотрудника"));
	if(inst)
	{
		m_recipient=inst;
		CString buf;
		m_api->GetItemName(m_recipient,buf);
		m_recipient_ctrl.SetWindowText(buf);
	}
}

void CAlertPropertiesDlg::OnSelectObjectBtn() 
{
	aplExtent ext;
	CaplInstance *inst=m_api->m_appr_mgr.
		SelectInstance(APL_MODE_SELECT_FOLDER|
					   APL_MODE_SELECT_CATEGORY|	
					   APL_MODE_SELECT_PRD|				
     			       APL_MODE_SELECT_PDF| 		    
					   APL_MODE_SELECT_DOC|  		    
					   APL_MODE_SELECT_BP|				
					   APL_MODE_SELECT_LOT|				
					   APL_MODE_SELECT_PRDINST|			
					   APL_MODE_SELECT_DOC_REVISION|	
					   APL_MODE_SELECT_BP_REVISION|		
					   APL_MODE_SELECT_PROJECT|			
					   APL_MODE_SELECT_ORG|				
					   APL_MODE_SELECT_PERSON|											
					   APL_MODE_SELECT_BPINST|
					   APL_MODE_SELECT_ORDER,
					    APL_T("Выберите связанный объект"));
	if(inst)
	{
		m_object=inst;
		CString buf;
		m_api->GetItemName(m_object,buf);
		m_object_ctrl.SetWindowText(buf);
	}
	
}

void CAlertPropertiesDlg::OnClearObject() 
{
	m_object=0;
	m_object_ctrl.SetWindowText(_T(""));
	
}
