// NoteDlg.cpp : implementation file
//

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

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

/////////////////////////////////////////////////////////////////////////////
// CNoteDlg dialog


CNoteDlg::CNoteDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CNoteDlg::IDD, pParent)
{
//	EnableAutomation();

	//{{AFX_DATA_INIT(CNoteDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	m_inst = 0;
	m_api = 0;
	m_ciNote = 0;
	m_parent = NULL;

	m_b_read_only=false;
}


void CNoteDlg::OnFinalRelease()
{
	// When the last reference for an automation object is released
	// OnFinalRelease is called.  The base class will automatically
	// deletes the object.  Add additional cleanup required for your
	// object before calling the base class.

	CaplResizableDialog::OnFinalRelease();
}

void CNoteDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CNoteDlg)
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDC_NOTE_INSERT_PICTURE, m_picture_insert_btn);
	DDX_Control(pDX, IDC_NOTE_INSERT_OBJECT, m_object_insert_btn);
	DDX_Control(pDX, IDC_NOTE_2, m_sub);
	DDX_Control(pDX, IDC_NOTE_1, m_super);
	DDX_Control(pDX, IDC_NOTE_FONTSIZE, m_sizefont);
	DDX_Control(pDX, IDC_NOTE_FONT, m_font);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_RICHEDIT1, m_richedit);
	DDX_Control(pDX, IDC_NOTE_UDERLINE, m_underline);
	DDX_Control(pDX, IDC_NOTE_STRICKOUT, m_strikeout);
	DDX_Control(pDX, IDC_NOTE_RIGHT, m_right);
	DDX_Control(pDX, IDC_NOTE_PASTE, m_paste);
	DDX_Control(pDX, IDC_NOTE_LEFT, m_left);
	DDX_Control(pDX, IDC_NOTE_ITALIC, m_italic);
	DDX_Control(pDX, IDC_NOTE_FONTSELECT, m_select_font);
	DDX_Control(pDX, IDC_NOTE_CUT, m_cut);
	DDX_Control(pDX, IDC_NOTE_COPY, m_copy);
	DDX_Control(pDX, IDC_NOTE_CENTER, m_center);
	DDX_Control(pDX, IDC_NOTE_BOLD, m_bold);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CNoteDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CNoteDlg)
	ON_NOTIFY(EN_IMECHANGE, IDC_RICHEDIT1, OnImechangeRichedit1)
	ON_CBN_CLOSEUP(IDC_NOTE_FONTSIZE, OnCloseupNoteFontsize)
	ON_CBN_CLOSEUP(IDC_NOTE_FONT, OnCloseupNoteFont)
	ON_NOTIFY(EN_SELCHANGE, IDC_RICHEDIT1, OnSelchangeRichedit1)
	ON_BN_CLICKED(IDC_NOTE_FONTSELECT, OnNoteFontselect)
	ON_BN_CLICKED(IDC_NOTE_UDERLINE, OnNoteUderline)
	ON_BN_CLICKED(IDC_NOTE_STRICKOUT, OnNoteStrickout)
	ON_BN_CLICKED(IDC_NOTE_RIGHT, OnNoteRight)
	ON_BN_CLICKED(IDC_NOTE_ITALIC, OnNoteItalic)
	ON_BN_CLICKED(IDC_NOTE_BOLD, OnNoteBold)
	ON_BN_CLICKED(IDC_NOTE_CENTER, OnNoteCenter)
	ON_BN_CLICKED(IDC_NOTE_1, OnNote1)
	ON_COMMAND(WM_FONTUPDATE, OnFontUpdate)
	ON_BN_CLICKED(IDC_NOTE_2, OnNote2)
	ON_BN_CLICKED(IDC_NOTE_LEFT, OnNoteLeft)
	ON_BN_CLICKED(IDC_NOTE_PASTE, OnNotePaste)
	ON_BN_CLICKED(IDC_NOTE_CUT, OnNoteCut)
	ON_BN_CLICKED(IDC_NOTE_COPY, OnNoteCopy)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

BEGIN_DISPATCH_MAP(CNoteDlg, CaplResizableDialog)
	//{{AFX_DISPATCH_MAP(CNoteDlg)
		// NOTE - the ClassWizard will add and remove mapping macros here.
	//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()

// Note: we add support for IID_INoteDlg to support typesafe binding
//  from VBA.  This IID must match the GUID that is attached to the 
//  dispinterface in the .ODL file.

// {3AFEBB85-16A2-42E3-94BB-416E32040017}
static const IID IID_INoteDlg =
{ 0x3afebb85, 0x16a2, 0x42e3, { 0x94, 0xbb, 0x41, 0x6e, 0x32, 0x4, 0x0, 0x17 } };

BEGIN_INTERFACE_MAP(CNoteDlg, CaplResizableDialog)
	INTERFACE_PART(CNoteDlg, IID_INoteDlg, Dispatch)
END_INTERFACE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CNoteDlg message handlers

BOOL CNoteDlg::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);   

	AddAnchor(IDC_RICHEDIT1,TOP_LEFT,BOTTOM_RIGHT);
	
	AddAnchor(IDOK, BOTTOM_RIGHT);
	AddAnchor(IDCANCEL, BOTTOM_RIGHT);
	//Настройка иконок на кнопках.

	API_DLG_TEST;
	if(m_inst==0 && m_ciNote==0)
	{
		EndDialog(0);
		return FALSE;
	}
	
	

	if(!CaplTranslate::IsNeedTranslate())
	{
		m_bold.SetIcon(GetAplTableIco(APL_TABLE_BOLD));
		m_italic.SetIcon(GetAplTableIco(APL_TABLE_ITALIC));
		m_underline.SetIcon(GetAplTableIco(APL_TABLE_UNDERLINE));
	}
	else
	{
		m_bold.SetIcon(GetAplTableIco(APL_TABLE_BOLD_EN));
		m_italic.SetIcon(GetAplTableIco(APL_TABLE_ITALIC_EN));
		m_underline.SetIcon(GetAplTableIco(APL_TABLE_UNDERLINE_EN));
	}

	m_strikeout.SetIcon(GetAplTableIco(APL_TABLE_STRIKEOUT));

	m_bold.SetTooltipText( APL_T("Выделять жирным"));
	m_italic.SetTooltipText( APL_T("Выделять курсивом"));
	m_underline.SetTooltipText( APL_T("Выделять подчеркивание"));
	m_strikeout.SetTooltipText( APL_T("Перечеркивать"));

	
	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("Выбрать шрифт"));

	m_super.SetIcon(GetAplTableIco(51));
	m_super.SetTooltipText( APL_T("Верхний индекс"));

	m_sub.SetIcon(GetAplTableIco(52));
	m_sub.SetTooltipText( APL_T("Нижний индекс"));

	//Добавление шрифтов.
	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();

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

	if(m_b_read_only)
	{
		m_richedit.SetReadOnly(TRUE);
		m_ok_btn.ShowWindow(SW_HIDE);
		m_picture_insert_btn.EnableWindow(FALSE);
		m_object_insert_btn.EnableWindow(FALSE);
		m_sub.EnableWindow(FALSE);
		m_super.EnableWindow(FALSE);
		m_sizefont.EnableWindow(FALSE);
		m_font.EnableWindow(FALSE);
		m_underline.EnableWindow(FALSE);
		m_strikeout.EnableWindow(FALSE);
		m_right.EnableWindow(FALSE);
		m_paste.EnableWindow(FALSE);
		m_left.EnableWindow(FALSE);
		m_italic.EnableWindow(FALSE);
		m_select_font.EnableWindow(FALSE);
		m_cut.EnableWindow(FALSE);
		m_copy.EnableWindow(FALSE);
		m_center.EnableWindow(FALSE);
		m_bold.EnableWindow(FALSE);
	}

	if(0!=m_ciNote)
	{
		long size;
		m_api->m_data.NET_GetBlobSize(m_ciNote,m_api->m_appr_mgr.a_note_source,size);
		if(size>0)
		{
			BYTE *rtfbuf=new BYTE[size];
			long size1=size;
			if(!m_api->m_data.NET_LoadBlob2Memory(m_ciNote,m_api->m_appr_mgr.a_note_source,rtfbuf,size1))
			{		
				AfxMessageBox( APL_T("Не могу прочитать текст из базы данных"));
			}
			else
			{
				CString buf=rtfbuf;
				m_richedit.SetRTF(buf);
			}
			delete rtfbuf;
		}
	}
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CNoteDlg::OnImechangeRichedit1(NMHDR* pNMHDR, LRESULT* pResult) 
{
	SELCHANGE *pSelChange = reinterpret_cast<SELCHANGE *>(pNMHDR);
	// TODO: The control will not send this notification unless you override the
	// CResizableDialog::OnInitDialog() function to send the EM_SETEVENTMASK message
	// to the control with the ENM_SELCHANGE flag ORed into the lParam mask.
	

//	m_fBulletedBtn.SetState(m_content.ParagraphIsBulleted());

	*pResult = 0;
}

void CNoteDlg::OnCloseupNoteFontsize() 
{
	CString font;
	int cur = m_sizefont.GetCurSel();
	m_sizefont.GetLBText(cur, font);
	m_richedit.SetFontSize(_atoi(font));
	m_richedit.SetFocus();
}

void CNoteDlg::OnCloseupNoteFont() 
{
	CString font;
	int cur = m_font.GetCurSel();
	m_font.GetLBText(cur,font);
	m_richedit.SetFontName(font);
	m_richedit.SetFocus();
}

void CNoteDlg::OnSelchangeRichedit1(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(-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);
	
	if(m_richedit.CanPaste()) m_paste.EnableWindow();
	else m_paste.EnableWindow(FALSE);
	
	m_bold.SetState(m_richedit.SelectionIsBold());
	m_italic.SetState(m_richedit.SelectionIsItalic());
	m_underline.SetState(m_richedit.SelectionIsUnderlined());
	m_strikeout.SetState(m_richedit.SelectionIsStrikeouted());

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

	m_super.SetState(m_richedit.SelectionIsSuperscribe());
	m_sub.SetState(m_richedit.SelectionIsSubscribe());
	
	m_richedit.SetFocus();
	
	*pResult = 0;
}

void CNoteDlg::OnNoteFontselect() 
{
	m_richedit.SelectFont();
}

void CNoteDlg::OnNoteUderline() 
{
	m_richedit.SetSelectionUnderlined();
	m_richedit.SetFocus();
	m_underline.SetState(m_richedit.SelectionIsUnderlined());
}

void CNoteDlg::OnNoteStrickout() 
{
	m_richedit.SetSelectionStrikeouted();
	m_richedit.SetFocus();
	m_strikeout.SetState(m_richedit.SelectionIsStrikeouted());
}

void CNoteDlg::OnNoteRight() 
{
	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 CNoteDlg::OnNoteItalic() 
{
	m_richedit.SetSelectionItalic();
	m_richedit.SetFocus();
	m_italic.SetState(m_richedit.SelectionIsItalic());
}

void CNoteDlg::OnNoteBold() 
{
	m_richedit.SetSelectionBold();
	m_richedit.SetFocus();
	m_bold.SetState(m_richedit.SelectionIsBold());
}

void CNoteDlg::OnNoteCenter() 
{
	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 CNoteDlg::OnNote1() 
{
	m_richedit.SetSuperscribe();
	m_super.SetState(m_richedit.SelectionIsSuperscribe());
	m_sub.SetState(m_richedit.SelectionIsSubscribe());
}

void CNoteDlg::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);

	m_bold.SetState(m_richedit.SelectionIsBold());
	m_italic.SetState(m_richedit.SelectionIsItalic());
	m_underline.SetState(m_richedit.SelectionIsUnderlined());
	m_strikeout.SetState(m_richedit.SelectionIsStrikeouted());

	m_super.SetState(m_richedit.SelectionIsSuperscribe());
	m_sub.SetState(m_richedit.SelectionIsSubscribe());
}


void CNoteDlg::OnNote2() 
{
	m_richedit.SetSubscribe();
	m_super.SetState(m_richedit.SelectionIsSuperscribe());
	m_sub.SetState(m_richedit.SelectionIsSubscribe());
}

void CNoteDlg::OnNoteLeft() 
{
	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 CNoteDlg::OnNotePaste() 
{
	m_richedit.Paste();
	m_richedit.SetFocus();
}

void CNoteDlg::OnNoteCut() 
{
	m_richedit.Cut();
	m_richedit.SetFocus();
}

void CNoteDlg::OnNoteCopy() 
{
	m_richedit.Copy();
	m_richedit.SetFocus();
}

void CNoteDlg::OnOK() 
{
	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;
	TCHAR *sbuf=name.GetBuffer(4096);
	GetTempFileName(tmp,_T("rtf"),TRUE,sbuf);
	name.ReleaseBuffer();

	if(!file.Open(name, CFile::modeCreate|CFile::modeWrite))
	{
		AfxMessageBox( APL_T("Не могу создать файл \"") + name +_T("\""));
		return;
	}
	file.WriteString(rtf);
	file.Close();

	if(0==m_ciNote)
	{
		CaplInstance *note = m_api->m_data.CreateInstance(m_api->m_appr_mgr.e_note);
		if(note==0) {AfxMessageBox( APL_T("Не могу создать элемент БД")); return;}
		m_ciNote = note;
	}

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

	CaplResizableDialog::OnOK();
}

CString CNoteDlg::GetUserName(CaplAPI *api)
{
	if(api==0) return _T("");
	CString name;
	CaplInstance *pers=api->m_appr_mgr.GetCurrentPerson();
	if(pers!=0) api->m_appr_mgr.GetPersonName(pers,name);
	if(pers) name+=_T(" (");
	name+= api->m_data.GetNameCurrUser();
	if(pers) name+=_T(")");
	return name;
}
