// ApprNoteDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ApprNoteDlg.h"
#include <afxdlgs.h>

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

/////////////////////////////////////////////////////////////////////////////
// CApprNoteDlg dialog


CApprNoteDlg::CApprNoteDlg(CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(CApprNoteDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CApprNoteDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	m_appr= NULL;
	m_item= NULL;
	m_api = 0;
	m_parent = NULL;
}


void CApprNoteDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CApprNoteDlg)
	DDX_Control(pDX, IDC_APPRNOTE_FONTSIZE, m_sizefont);
	DDX_Control(pDX, IDC_APPRNOTE_FONTNAME, m_font);
	DDX_Control(pDX, IDC_APPRNOTE_ARIGHT, m_right);
	DDX_Control(pDX, IDC_APPRNOTE_PASTE, m_paste);
	DDX_Control(pDX, IDC_APPRNOTE_ALEFT, m_left);
	DDX_Control(pDX, IDC_APPRNOTE_SELFONT, m_select_font);
	DDX_Control(pDX, IDC_APPRNOTE_CUT, m_cut);
	DDX_Control(pDX, IDC_APPRNOTE_COPY, m_copy);
	DDX_Control(pDX, IDC_APPRNOTE_ACENTER, m_center);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CApprNoteDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CApprNoteDlg)
	ON_BN_CLICKED(IDC_APPRNOTE_CUT, OnApprnoteCut)
	ON_BN_CLICKED(IDC_APPRNOTE_COPY, OnApprnoteCopy)
	ON_BN_CLICKED(IDC_APPRNOTE_PASTE, OnApprnotePaste)
	ON_BN_CLICKED(IDC_APPRNOTE_SELFONT, OnApprnoteSelfont)
	ON_BN_CLICKED(IDC_APPRNOTE_ALEFT, OnApprnoteAleft)
	ON_BN_CLICKED(IDC_APPRNOTE_ACENTER, OnApprnoteAcenter)
	ON_BN_CLICKED(IDC_APPRNOTE_ARIGHT, OnApprnoteAright)
	ON_CBN_CLOSEUP(IDC_APPRNOTE_FONTNAME, OnCloseupApprnoteFontname)
	ON_CBN_CLOSEUP(IDC_APPRNOTE_FONTSIZE, OnCloseupApprnoteFontsize)
	ON_COMMAND(WM_FONTUPDATE, OnFontUpdate)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


void CApprNoteDlg::SetAnchors()
{
//	AddAnchor(IDC_RICHEDIT1_NOTE,TOP_LEFT,BOTTOM_RIGHT);
}

void CApprNoteDlg::AddFonts()
{
	
	//Добавление шрифтов.
	CStringArray fonts;
	m_richedit->GetSystemFonts(fonts);
	
	for(int i=0; i<fonts.GetSize();i++)
		m_font.AddString(fonts.GetAt(i));
	m_sizefont.SetCurSel(2);
	m_font.SelectString(-1,_T("Arial"));

	m_richedit->SetEventMask(m_richedit->GetEventMask()|
							ENM_CHANGE | ENM_UPDATE | ENM_SCROLL |
							ENM_KEYEVENTS | ENM_REQUESTRESIZE|
							ENM_DROPFILES | ENM_PROTECTED | ENM_CORRECTTEXT |
							ENM_SCROLLEVENTS | ENM_DRAGDROPDONE|
							ENM_MOUSEEVENTS | ENM_SELCHANGE);

	CString font;
	m_richedit->SetFontSize(10);
	m_font.GetWindowText(font);
	m_richedit->SetFontName(font);
	m_richedit->SetFocus();


}

bool CApprNoteDlg::GetLastNote()		//true, если не надо создавать Note
{
	if((m_api==NULL)||(m_appr==NULL))
		return false;
	
	aplExtent notes;
	CString descr, date;
	int i=0,cur=0;
	COleDateTime notetime,nt1;

	if(m_mode!=_T("Edit"))
		return false;			//надо создавать Note  (mode == "Create");

	m_api->m_appr_mgr.FindAssociatedNotes(m_item, notes); // читаем примечания в кэш
	m_api->m_data.GetAttr(m_appr, m_api->m_appr_mgr.a_appr_po_item_note, m_note);

	if(m_note)
//	if(notes.GetSize()>0)
	{
	//	AfxMessageBox(_T(">0"));
		m_bNewNote=false;
//		m_api->m_data.GetAttr(notes[0], m_api->m_appr_mgr.a_note_date, date);
//		aplString2Date(date,notetime);
//		notetime.SetStatus(COleDateTime::valid);
//		for(i=1;i<notes.GetSize();i++)
//		{
//			m_api->m_data.GetAttr(notes[i], m_api->m_appr_mgr.a_note_date, date);
//			aplString2Date(date,nt1);
//			nt1.SetStatus(COleDateTime::valid);
//			if (nt1>notetime)
//			{
//				notetime=nt1;
//				cur=i;
//			}
//		}
//		m_note=notes[cur];

		m_api->m_data.GetAttr(m_note, m_api->m_appr_mgr.a_note_descr, descr);

		SetRTF(m_note);	
		return true;		//не надо создавать Note
	}
	else
	{
		m_bNewNote=true;
		return false;		//надо создавать Note
	}

}

void CApprNoteDlg::SetRTF(CaplInstance *note)
{
	if(note==0) return;
	long size=0;
	if(!m_api->m_data.NET_GetBlobSize(note,m_api->m_appr_mgr.a_note_source, size)) return;
	if(size==0)
	{
		m_richedit->SetRTF(_T(""));
		return;
	}
	BYTE *c = new BYTE[size];
	m_api->m_data.NET_LoadBlob2Memory(note,m_api->m_appr_mgr.a_note_source,c,size);
	CString rtf;
#if _MSC_VER >= 1400
	rtf = (const char*)c;
#else
	rtf += c;
#endif
	delete c;
	m_richedit->SetRTF(rtf);
}

void CApprNoteDlg::SaveNote()
{
	if(m_bNewNote)
	{
		if(m_richedit->GetTextLength()>0)
			OKClicked();
		else
			*m_pNote=NULL;
	}
	else
	{
		if(m_richedit->GetTextLength()>0)
			OKClickedExists(m_note);
	}
}

/////////////////////////////////////////////////////////////////////////////
// CApprNoteDlg message handlers

BOOL CApprNoteDlg::OnInitDialog() 
{
	CaplTranslateDialog::OnInitDialog();
	
	SetAnchors();
	
	
	m_left.SetIcon(GetAplTableIco(14));
	m_left.SetTooltipText( APL_T("Выравнивать по левому краю"));

	m_right.SetIcon(GetAplTableIco(16));
	m_right.SetTooltipText( APL_T("Выравнивать по правому краю"));
	
	m_center.SetIcon(GetAplTableIco(15));
	m_center.SetTooltipText( APL_T("Выравнивать по центру"));
	
	m_copy.SetIcon(GetAplTableIco(APL_TABLE_COPY));
	m_copy.SetTooltipText( APL_T("Копировать в буфер"));

	m_cut.SetIcon(GetAplTableIco(APL_TABLE_CUT));
	m_cut.SetTooltipText( APL_T("Вырезать"));

	m_paste.SetIcon(GetAplTableIco(APL_TABLE_PASTE));
	m_paste.SetTooltipText( APL_T("Вставить из буфера"));

	m_select_font.SetIcon(GetAplTableIco(9));
	m_select_font.SetTooltipText( APL_T("Выбрать шрифт"));
	

	return TRUE;  
}

void CApprNoteDlg::OnCancel()
{
//	CaplTranslateDialog::OnCancel();
}

void CApprNoteDlg::OnApprnoteCut() 
{
	// TODO: Add your control notification handler code here
	m_richedit->Cut();
	m_richedit->SetFocus();
}

void CApprNoteDlg::OnApprnoteCopy() 
{
	// TODO: Add your control notification handler code here
	m_richedit->Copy();
	m_richedit->SetFocus();
}

void CApprNoteDlg::OnApprnotePaste() 
{
	// TODO: Add your control notification handler code here
	m_richedit->Paste();
	m_richedit->SetFocus();
}

void CApprNoteDlg::OnApprnoteSelfont() 
{
	// TODO: Add your control notification handler code here
	m_richedit->SelectFont();
}

void CApprNoteDlg::OnApprnoteAleft() 
{
	// TODO: Add your control notification handler code here
	m_richedit->SetParagraphLeft();
	m_center.SetState(m_richedit->ParagraphIsCentered());
	m_left.SetState(m_richedit->ParagraphIsLeft());
	m_right.SetState(m_richedit->ParagraphIsRight());
	m_richedit->SetFocus();
}

void CApprNoteDlg::OnApprnoteAcenter() 
{
	// TODO: Add your control notification handler code here
	m_richedit->SetParagraphCenter();
	m_center.SetState(m_richedit->ParagraphIsCentered());
	m_left.SetState(m_richedit->ParagraphIsLeft());
	m_right.SetState(m_richedit->ParagraphIsRight());
	m_richedit->SetFocus();
}

void CApprNoteDlg::OnApprnoteAright() 
{
	// TODO: Add your control notification handler code here
	m_richedit->SetParagraphRight();
	m_center.SetState(m_richedit->ParagraphIsCentered());
	m_left.SetState(m_richedit->ParagraphIsLeft());
	m_right.SetState(m_richedit->ParagraphIsRight());
	m_richedit->SetFocus();
}

void CApprNoteDlg::OnCloseupApprnoteFontname() 
{
	// TODO: Add your control notification handler code here
	CString font;
	int cur = m_font.GetCurSel();
	m_font.GetLBText(cur,font);
	m_richedit->SetFontName(font);
	m_richedit->SetFocus();
}

void CApprNoteDlg::OnCloseupApprnoteFontsize() 
{
	// TODO: Add your control notification handler code here
	CString font;
	int cur = m_sizefont.GetCurSel();
	m_sizefont.GetLBText(cur, font);
	m_richedit->SetFontSize(_atoi(font));

	CString buf;
	buf.Format(_T("%i"), m_richedit->GetSelectionFontSize());
	int ind = m_sizefont.FindStringExact(0,buf);
	if(ind == LB_ERR) 
		ind = m_sizefont.AddString(buf);
	m_sizefont.SetCurSel(ind);
	
	m_richedit->SetFocus();
}

void CApprNoteDlg::SelChangeRE(NMHDR* pNMHDR, LRESULT* pResult)
{
	
	SELCHANGE *pSelChange = reinterpret_cast<SELCHANGE *>(pNMHDR);
	// TODO: The control will not send this notification unless you override the
	// CDialog::OnInitDialog() function to send the EM_SETEVENTMASK message
	// to the control with the ENM_SELCHANGE flag ORed into the lParam mask.
	
	long nLength= m_richedit->GetTextLength();
	
	char * buffer = NULL;
	if (m_richedit->CanPaste() && OpenClipboard()) 
	{
		HANDLE hData = GetClipboardData(CF_TEXT);
		buffer = (char*)GlobalLock(hData);
		GlobalUnlock(hData);
		CloseClipboard();
	}
	
	if(buffer)
		nLength+=strlen(buffer);
	if (m_richedit->GetLimitText() < nLength+2)
		m_richedit->LimitText(nLength+2);	

	CString buf;
	buf.Format(_T("%i"), m_richedit->GetSelectionFontSize());
	int ind = m_sizefont.FindStringExact(0,buf);
	if(ind == LB_ERR) 
		ind = m_sizefont.AddString(buf);
	m_sizefont.SetCurSel(ind);
	
	buf= m_richedit->GetSelectionFontName();
	ind = m_font.FindStringExact(0,buf);
	if(ind == LB_ERR) 
		ind = m_font.AddString(buf);
	m_font.SetCurSel(ind);
	
	if(m_richedit->CanPaste()) m_paste.EnableWindow();
	else m_paste.EnableWindow(FALSE);
	

	m_left.SetState(m_richedit->ParagraphIsLeft());
	m_center.SetState(m_richedit->ParagraphIsCentered());
	m_right.SetState(m_richedit->ParagraphIsRight());

	
	*pResult = 0;
}

void CApprNoteDlg::OKClicked()
{
//	AfxMessageBox(_T("OkClicked"));
	
	CString rtf = m_richedit->GetRTF();
	CStdioFile file;
	CString tmp, buf;
	tmp.GetEnvironmentVariable(_T("temp"));
	TCHAR buffer[1024]=_T("");
	m_richedit->GetLine(0,buffer, 1024);
	buf+=buffer;
	if(buf.Find(_T("."),0)>-1) buf = buf.Left(buf.Find(_T(".")));
	if(buf.ReverseFind(10)>-1) buf = buf.Left(buf.ReverseFind(10));
	if(buf.ReverseFind(13)>-1) buf = buf.Left(buf.ReverseFind(13));
	
	CString name = buf;
	if(!file.Open(tmp+_T("\\")+name+_T(".rtf"), CFile::modeCreate|CFile::modeWrite))
	{
		name = _T("123");
		if(!file.Open(tmp+_T("\\")+name+_T(".rtf"), CFile::modeCreate|CFile::modeWrite))
		{
			AfxMessageBox( APL_T("Не могу создать файл \"")+tmp+_T("\\123.rtf\"."));
			return;
		}
	}
	file.WriteString(rtf);
	file.Close();
	CaplInstance *note = m_api->m_data.CreateInstance(m_api->m_appr_mgr.e_note);
	if(note==0) {AfxMessageBox( APL_T("Не могу создать элемент БД")); return;}

	if(m_item!=NULL)
		m_api->m_data.PutAttr(note, m_api->m_appr_mgr.a_note_item, m_item);
	if(m_appr!=NULL)
		m_api->m_data.PutAttr(m_appr, m_api->m_appr_mgr.a_appr_po_item_note, note);
	

	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_descr, buf);
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_parent,m_parent);
	CaplInstance *pers=m_api->m_appr_mgr.GetCurrentPerson();
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_author,pers);
	CString date;
	COleDateTime time = COleDateTime::GetCurrentTime();
	aplDate2String(time,date);
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_date,date);
	long code=0;
	if(!m_api->m_data.NET_SaveBlob(note,m_api->m_appr_mgr.a_note_source,tmp+_T("\\")+name+_T(".rtf"),code))
	{
		AfxMessageBox( APL_T("Не могу сохранить текст в базу данных"));
		m_api->m_data.DeleteInstance(note);
		return;
	}
	m_api->m_data.NET_SaveChanges();
	file.Remove(tmp+_T("\\")+name+_T(".rtf"));
	*m_pNote = note;
}

void CApprNoteDlg::OKClickedExists(CaplInstance *note)
{
	CString rtf = m_richedit->GetRTF();
	CStdioFile file;
	CString tmp, buf;
	tmp.GetEnvironmentVariable(_T("temp"));
	TCHAR buffer[1024]=_T("");
	m_richedit->GetLine(0,buffer, 1024);
	buf+=buffer;
	if(buf.Find(_T("."),0)>-1) buf = buf.Left(buf.Find(_T(".")));
	if(buf.ReverseFind(10)>-1) buf = buf.Left(buf.ReverseFind(10));
	if(buf.ReverseFind(13)>-1) buf = buf.Left(buf.ReverseFind(13));
	
	CString name = buf;
	if(!file.Open(tmp+_T("\\")+name+_T(".rtf"), CFile::modeCreate|CFile::modeWrite))
	{
		name = _T("123");
		if(!file.Open(tmp+_T("\\")+name+_T(".rtf"), CFile::modeCreate|CFile::modeWrite))
		{
			AfxMessageBox( APL_T("Не могу создать файл \"")+tmp+_T("\\123.rtf\"."));
			return;
		}
	}
	file.WriteString(rtf);
	file.Close();
//	CaplInstance *note = m_api->m_data.CreateInstance(m_api->m_appr_mgr.e_note);
	if(note==0) {AfxMessageBox( APL_T("Не могу создать элемент БД")); return;}
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_item, m_item);
	m_api->m_data.PutAttr(m_appr, m_api->m_appr_mgr.a_appr_po_item_note, note);
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_descr, buf);
//	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_parent,m_parent);
	CaplInstance *pers=m_api->m_appr_mgr.GetCurrentPerson();
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_author,pers);
	CString date;
	COleDateTime time = COleDateTime::GetCurrentTime();
	aplDate2String(time,date);
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_date,date);
	long code=0;
	if(!m_api->m_data.NET_SaveBlob(note,m_api->m_appr_mgr.a_note_source,tmp+_T("\\")+name+_T(".rtf"),code))
	{
		AfxMessageBox( APL_T("Не могу сохранить текст в базу данных"));
		m_api->m_data.DeleteInstance(note);
		return;
	}
	m_api->m_data.NET_SaveChanges();
	file.Remove(tmp+_T("\\")+name+_T(".rtf"));
}

void CApprNoteDlg::OnFontUpdate()
{
	CString buf;
	buf.Format(_T("%i"), m_richedit->GetSelectionFontSize());
	int ind = m_sizefont.FindStringExact(-1,buf);
	if(ind<0) ind = m_sizefont.AddString(buf);
	m_sizefont.SetCurSel(ind);
	
	buf= m_richedit->GetSelectionFontName();
	ind = m_font.FindStringExact(-1,buf);
	if(ind<0) ind = m_font.AddString(buf);
	m_font.SetCurSel(ind);
}
