// TitleDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TitleDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CTitleDlg dialog


CTitleDlg::CTitleDlg(CaplReportMgr *ReportMgr, CReportSheet *pSheet, CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(CTitleDlg::IDD, pParent)
{
	ASSERT(ReportMgr);
	ASSERT(pSheet);

	m_ReportMgr = ReportMgr;
	m_pSheet = pSheet;

	memset(&m_TitleFont, 0, sizeof(LOGFONT));
	m_TitleFont.lfHeight = 12;
	memcpy(&m_TitleFont.lfFaceName, &_T("Arial"), 6);
	m_TitleFont.lfCharSet = RUSSIAN_CHARSET;
	m_TitleFont.lfPitchAndFamily = DEFAULT_PITCH;
	m_TitleFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
	m_TitleFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
	m_TitleFont.lfQuality = DEFAULT_QUALITY;

	//{{AFX_DATA_INIT(CTitleDlg)
	m_sFontName = m_TitleFont.lfFaceName;
	m_iFontSize = m_TitleFont.lfHeight;
	m_dHeight = 10.0;
	m_dLeft = 0.0;
	m_dRight = 0.0;
	m_dTop = 0.0;
	m_dLineWidth = (double)(AfxGetApp()->GetProfileInt(_T("DefaultSettings"),_T("LineWidth"), 1))/10;
	//}}AFX_DATA_INIT

	m_align = AT_VCENTER|AT_CENTER;
}


void CTitleDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTitleDlg)
	DDX_Control(pDX, IDC_TOP_RIGHT, m_tr_btn);
	DDX_Control(pDX, IDC_TOP_LEFT, m_tl_btn);
	DDX_Control(pDX, IDC_TOP_CENTER, m_tc_btn);
	DDX_Control(pDX, IDC_CENTER_RIGHT, m_cr_btn);
	DDX_Control(pDX, IDC_CENTER_LEFT, m_cl_btn);
	DDX_Control(pDX, IDC_CENTER, m_center_btn);
	DDX_Control(pDX, IDC_BOTTOM_LEFT, m_bl_btn);
	DDX_Control(pDX, IDC_BOTTOM_CENTER, m_bc_btn);
	DDX_Control(pDX, IDC_BOTTEM_RIGHT, m_br_btn);
	DDX_Control(pDX, IDC_UP_COLUMN, m_up_column_btn);
	DDX_Control(pDX, IDC_DOWN_COLUMN, m_down_column_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_DEL_COLUMN, m_del_column_btn);
	DDX_Control(pDX, IDC_CONFIG_FONT, m_config_font_btn);
	DDX_Control(pDX, IDC_ADD_COLUMN, m_add_column_btn);
	DDX_Control(pDX, IDC_COLUMNS_LIST, m_ColumnListCtrl);
	DDX_Text(pDX, IDC_FONT_NAME, m_sFontName);
	DDX_Text(pDX, IDC_FONT_SIZE, m_iFontSize);
	DDX_Text(pDX, IDC_HEIGHT, m_dHeight);
	DDX_Text(pDX, IDC_LEFT, m_dLeft);
	DDX_Text(pDX, IDC_RIGHT, m_dRight);
	DDX_Text(pDX, IDC_TOP, m_dTop);
	DDX_Text(pDX, IDC_LINE_WIDTH, m_dLineWidth);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_USE_EVEN_CHECK, m_use_even_check);
	DDX_Control(pDX, IDC_USE_EVEN_COMBO, m_use_even_combo);
}


BEGIN_MESSAGE_MAP(CTitleDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CTitleDlg)
	ON_BN_CLICKED(IDC_CONFIG_FONT, OnConfigFont)
	ON_BN_CLICKED(IDC_ADD_COLUMN, OnAddColumn)
	ON_BN_CLICKED(IDC_DEL_COLUMN, OnDelColumn)
	ON_BN_CLICKED(IDC_CALC_COLUMNS_WIDTH, OnCalcColumnsWidth)
	ON_BN_CLICKED(IDC_UP_COLUMN, OnUpColumn)
	ON_BN_CLICKED(IDC_DOWN_COLUMN, OnDownColumn)
	ON_BN_CLICKED(IDC_TOP_LEFT, OnTopLeft)
	ON_BN_CLICKED(IDC_TOP_CENTER, OnTopCenter)
	ON_BN_CLICKED(IDC_TOP_RIGHT, OnTopRight)
	ON_BN_CLICKED(IDC_CENTER_RIGHT, OnCenterRight)
	ON_BN_CLICKED(IDC_CENTER_LEFT, OnCenterLeft)
	ON_BN_CLICKED(IDC_CENTER, OnCenter)
	ON_BN_CLICKED(IDC_BOTTOM_LEFT, OnBottomLeft)
	ON_BN_CLICKED(IDC_BOTTOM_CENTER, OnBottomCenter)
	ON_BN_CLICKED(IDC_BOTTEM_RIGHT, OnBottemRight)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_USE_EVEN_CHECK, &CTitleDlg::OnBnClickedUseEvenCheck)
	ON_CBN_SELCHANGE(IDC_USE_EVEN_COMBO, &CTitleDlg::OnCbnSelchangeUseEvenCombo)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTitleDlg message handlers

BOOL CTitleDlg::OnInitDialog() 
{
	CaplTranslateDialog::OnInitDialog();
	
	m_ok_btn.SetIcon(aplGetStdIco16(APL_STD_OK));
	m_ok_btn.SetFlat(FALSE);
	m_cancel_btn.SetIcon(aplGetStdIco16(APL_STD_CANCEL));
	m_cancel_btn.SetFlat(FALSE);

	m_config_font_btn.SetIcon(aplGetButtonIco(APL_24_SELECT));
	m_config_font_btn.SetWindowText(_T(""));
	m_add_column_btn.SetIcon(aplGetButtonIco(APL_24_PLUS));
	m_add_column_btn.SetWindowText(_T(""));
	m_del_column_btn.SetIcon(aplGetButtonIco(APL_24_DELETE));
	m_del_column_btn.SetWindowText(_T(""));

	m_up_column_btn.SetIcon(aplGetStdIco16(APL_STD_TOP));
	m_up_column_btn.SetWindowText(_T(""));
	m_down_column_btn.SetIcon(aplGetStdIco16(APL_STD_BOTTOM));
	m_down_column_btn.SetWindowText(_T(""));

	CBitmap bm;
	CImageList il;
	bm.LoadBitmap(IDB_TEXT_FORMAT);
	il.Create(16, 16, ILC_COLOR24|ILC_MASK, 0, 100);
	il.Add(&bm, RGB(192,192,192));
	
	m_tl_btn.SetIcon(il.ExtractIcon(0));
	m_tl_btn.SetWindowText(_T(""));
	
	m_tc_btn.SetIcon(il.ExtractIcon(1));
	m_tc_btn.SetWindowText(_T(""));
	
	m_tr_btn.SetIcon(il.ExtractIcon(2));
	m_tr_btn.SetWindowText(_T(""));
	
	m_cr_btn.SetIcon(il.ExtractIcon(5));
	m_cr_btn.SetWindowText(_T(""));
	
	m_cl_btn.SetIcon(il.ExtractIcon(3));
	m_cl_btn.SetWindowText(_T(""));
	
	m_center_btn.SetIcon(il.ExtractIcon(4));
	m_center_btn.SetWindowText(_T(""));
	
	m_bl_btn.SetIcon(il.ExtractIcon(6));
	m_bl_btn.SetWindowText(_T(""));
	
	m_bc_btn.SetIcon(il.ExtractIcon(7));
	m_bc_btn.SetWindowText(_T(""));
	
	m_br_btn.SetIcon(il.ExtractIcon(8));
	m_br_btn.SetWindowText(_T(""));
	
	CRect rect;
	m_ColumnListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
	m_ColumnListCtrl.GetClientRect(&rect);

	m_ColumnListCtrl.InsertColumn(0, _T(""), LVCFMT_LEFT, int(rect.Width()*0.05));
	m_ColumnListCtrl.InsertColumn(1, APL_T("Заголовок"), LVCFMT_LEFT, int(rect.Width()*0.6));
	m_ColumnListCtrl.InsertColumn(2, APL_T("Ширина"), LVCFMT_LEFT, int(rect.Width()*0.3));

	m_use_even_combo.AddString(ID_STRING_EVEN);
	m_use_even_combo.AddString(ID_STRING_ODD);

	m_use_even_combo.SelectString(0,ID_STRING_EVEN);
	m_use_even_check.SetCheck((m_align&AT_USE_EVEN)!=0);
	m_use_even_combo.EnableWindow((m_align&AT_USE_EVEN)!=0);

	SetCheck(m_align,false);
	
	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

void CTitleDlg::OnConfigFont() 
{
	if(!UpdateData(TRUE)) return;

	LOGFONT lfInitial = m_TitleFont;
	CDC *pDC = GetDC();
	lfInitial.lfHeight = -MulDiv(-lfInitial.lfHeight, ::GetDeviceCaps(pDC->m_hDC, LOGPIXELSY), 72);
	CFontDialog dlg(&lfInitial);
	dlg.m_cf.Flags |=CF_LIMITSIZE;
	dlg.m_cf.nSizeMax = 1638;
	dlg.m_cf.nSizeMin = 1;
	if(dlg.DoModal()==IDOK)
	{
		m_TitleFont = dlg.m_lf;
		m_TitleFont.lfHeight = dlg.GetSize()/10;
	}
	ReleaseDC(pDC);

	m_sFontName = m_TitleFont.lfFaceName;
	m_iFontSize = m_TitleFont.lfHeight;

	UpdateData(FALSE);
}

void CTitleDlg::OnAddColumn() 
{
	CString buf;
	int cnt = m_ColumnListCtrl.GetItemCount();
	buf.Format(_T("%d"), cnt+1);
	int ind = m_ColumnListCtrl.InsertItem(cnt, buf);
	if(ind>-1)
	{
		m_ColumnListCtrl.SetItemEditType(ind, 1, aplTextCtrl);
		m_ColumnListCtrl.SetItemEditType(ind, 2, aplRealCtrl);
		m_ColumnListCtrl.SetItemText(ind, 2, _T("0.0"));
	}
}

void CTitleDlg::OnDelColumn() 
{
	int ind = m_ColumnListCtrl.GetNextItem(-1, LVIS_SELECTED);
	if(ind>-1)
	{
		m_ColumnListCtrl.DeleteItem(ind);
		CString buf;
		for(int i=ind; i<m_ColumnListCtrl.GetItemCount(); i++)
		{
			buf.Format(_T("%d"), i+1);
			m_ColumnListCtrl.SetItemText(i, 0, buf);
		}
		if(ind<m_ColumnListCtrl.GetItemCount())
			m_ColumnListCtrl.SetItemState(ind, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
		else if(ind>0)
			m_ColumnListCtrl.SetItemState(--ind, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
	}
}

void CTitleDlg::OnOK() 
{
	if(m_ColumnListCtrl.EndEdit()) return;
	if(!UpdateData()) return;
	try
	{
		//проверяем корректность данных
		if(m_dLeft<0) throw(APL_T("Отступ слева не может быть меньше нуля!"));
		if(m_dRight<0) throw(APL_T("Отступ справа не может быть меньше нуля!"));
		if(m_dTop<0) throw(APL_T("Отступ сверху не может быть меньше нуля!"));
		if(m_dHeight<=0) throw(APL_T("Высота заголовка не может быть меньше или равной нулю!"));
		if(m_dLineWidth<0) throw(APL_T("Толщина линий заголовка не может быть меньше нуля!"));

		//Проверяем ширину полей
		//Недопустима ширина в 0 мм и суммарное превышение ширины страницы с учетом отступов
		int i;
		int cnt;
		CString buf;
		double dCurWidth;
		double dWidth;
		double dSheetWidth;
		double dCurPos;
		CRectReportElement *pElem;

		cnt = m_ColumnListCtrl.GetItemCount();
		dWidth = 0;

		for(i=0; i<cnt; i++)
		{
			buf = m_ColumnListCtrl.GetItemText(i, 2);
			if(buf.IsEmpty())
			{
				buf.Format(APL_T("У поля с заголовком \"%s\" не задана ширина!"), m_ColumnListCtrl.GetItemText(i, 1));
				throw(buf);
			}
			dCurWidth = __atof(buf);
			if(dCurWidth<=0)
			{
				buf.Format(APL_T("Ширина поля не может быть меньше или равной нулю (поле: \"%s\")!"), m_ColumnListCtrl.GetItemText(i, 1));
				throw(buf);
			}
			dWidth+=dCurWidth;
		}

		dSheetWidth = (double)(m_pSheet->m_size.cx)/10-m_dLeft-m_dRight;

		if(dSheetWidth<dWidth)
		{
			buf.Format(APL_T("Суммарная ширина полей больше ширины области отображения на %.1f мм!\nСкорректируйте ширину одного или нескольких полей таблицы!"), dWidth-dSheetWidth);
			throw(buf);
		}
		else if(dSheetWidth>dWidth)
		{
			buf.Format(APL_T("Суммарная ширина полей меньше ширины области отображения на %.1f мм!\nСкорректируйте ширину одного или нескольких полей таблицы!"), dSheetWidth-dWidth);
			throw(buf);
		}

		//Создание элементов
		m_TitleFont.lfHeight*=10;
		
		dCurPos = m_dLeft;
		for(i=0; i<cnt; i++)
		{
			buf = m_ColumnListCtrl.GetItemText(i, 2);
			dCurWidth = __atof(buf);

			pElem = new CRectReportElement(m_ReportMgr);
			pElem->SetRect(CRect((int)(dCurPos*10), (int)(-m_dTop*10), (int)((dCurPos+dCurWidth)*10), (int)((-m_dTop-m_dHeight)*10)), 1);
			pElem->m_value.SetFont(m_TitleFont);
			pElem->m_value.SetText(m_ColumnListCtrl.GetItemText(i, 1));
			pElem->m_line_width = (int)(m_dLineWidth*10);
			pElem->m_value.m_align = m_align;
			m_pSheet->Add(pElem);
			dCurPos+=dCurWidth;
			pElem = NULL;
		}
	}
	catch(TCHAR* buf)
	{
		AfxMessageBox(buf, MB_OK|MB_ICONQUESTION);
		return;
	}
	catch(CString buf)
	{
		AfxMessageBox(buf, MB_OK|MB_ICONQUESTION);
		return;
	}
	catch(...)
	{
		AfxMessageBox(APL_T("Произошла неизвестная ошибка при создании заголовка!"), MB_OK|MB_ICONSTOP);
	}
	
	CaplTranslateDialog::OnOK();
}

void CTitleDlg::OnCancel() 
{
	if(m_ColumnListCtrl.EndEdit(false)) return;
	
	CaplTranslateDialog::OnCancel();
}

void CTitleDlg::OnCalcColumnsWidth() 
{
	if(!UpdateData()) return;
	int cnt;
	int i;
	double width;
	double SheetWidth;
	CString buf;

	cnt = m_ColumnListCtrl.GetItemCount();
	SheetWidth = (double)(m_pSheet->m_size.cx)/10;
	SheetWidth = SheetWidth-m_dLeft-m_dRight;
	width = SheetWidth/(double)cnt;

	buf.Format(_T("%.1f"), width);
	for(i=0; i<cnt; i++)
		m_ColumnListCtrl.SetItemText(i, 2, buf);
}

void CTitleDlg::OnUpColumn() 
{
	int ind = m_ColumnListCtrl.GetNextItem(-1, LVIS_SELECTED);
	if(ind>0)
	{
		CString name, width;
		name = m_ColumnListCtrl.GetItemText(ind, 1);
		width = m_ColumnListCtrl.GetItemText(ind, 2);
		m_ColumnListCtrl.SetItemText(ind, 1, m_ColumnListCtrl.GetItemText(ind-1, 1));
		m_ColumnListCtrl.SetItemText(ind, 2, m_ColumnListCtrl.GetItemText(ind-1, 2));
		m_ColumnListCtrl.SetItemText(--ind, 1, name);
		m_ColumnListCtrl.SetItemText(ind, 2, width);
		m_ColumnListCtrl.SetItemState(ind, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
	}
}

void CTitleDlg::OnDownColumn() 
{
	int ind = m_ColumnListCtrl.GetNextItem(-1, LVIS_SELECTED);
	if(ind>-1 && ind<m_ColumnListCtrl.GetItemCount()-1)
	{
		CString name, width;
		name = m_ColumnListCtrl.GetItemText(ind, 1);
		width = m_ColumnListCtrl.GetItemText(ind, 2);
		m_ColumnListCtrl.SetItemText(ind, 1, m_ColumnListCtrl.GetItemText(ind+1, 1));
		m_ColumnListCtrl.SetItemText(ind, 2, m_ColumnListCtrl.GetItemText(ind+1, 2));
		m_ColumnListCtrl.SetItemText(++ind, 1, name);
		m_ColumnListCtrl.SetItemText(ind, 2, width);
		m_ColumnListCtrl.SetItemState(ind, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
	}
}

void CTitleDlg::OnTopLeft() 
{
	SetCheck(AT_TOP|AT_LEFT);
}

void CTitleDlg::OnTopCenter() 
{
	SetCheck(AT_TOP|AT_CENTER);
}

void CTitleDlg::OnTopRight() 
{
	SetCheck(AT_TOP|AT_RIGHT);
}

void CTitleDlg::OnCenterRight() 
{
	SetCheck(AT_VCENTER|AT_RIGHT);
}

void CTitleDlg::OnCenterLeft() 
{
	SetCheck(AT_VCENTER|AT_LEFT);
}

void CTitleDlg::OnCenter() 
{
	SetCheck(AT_VCENTER|AT_CENTER);
}

void CTitleDlg::OnBottomLeft() 
{
	SetCheck(AT_BOTTOM|AT_LEFT);
}

void CTitleDlg::OnBottomCenter() 
{
	SetCheck(AT_BOTTOM|AT_CENTER);
}

void CTitleDlg::OnBottemRight() 
{
	SetCheck(AT_BOTTOM|AT_RIGHT);
}

void CTitleDlg::SetCheck(UINT align, bool bChange)
{
	CString sEven;
	BOOL bCheck;
	BOOL bEven;
	m_tl_btn.SetState(0);
	m_tc_btn.SetState(0);
	m_tr_btn.SetState(0);
	m_cl_btn.SetState(0);
	m_center_btn.SetState(0);
	m_cr_btn.SetState(0);
	m_bl_btn.SetState(0);
	m_bc_btn.SetState(0);
	m_br_btn.SetState(0);
	m_use_even_combo.GetWindowText(sEven);
	bCheck = m_use_even_check.GetCheck();
	bEven = sEven.CompareNoCase(ID_STRING_EVEN);

	m_align&=07777;
	if(bCheck)
		m_align|=010000;

	if (bChange)
	{
		if (bEven)
		{
			m_align&=010077;
			m_align|=align<<6;
		}
		else
		{
			m_align&=017700;
			m_align|=align;
		}
	}
	else
	{
		if (bEven)
			align = m_align>>6;
		else
			align = m_align;
	}

	if(align&AT_TOP && align&AT_LEFT)
		m_tl_btn.SetState(1);
	else if(align&AT_TOP && align&AT_CENTER)
		m_tc_btn.SetState(1);
	else if(align&AT_TOP && align&AT_RIGHT)
		m_tr_btn.SetState(1);
	else if(align&AT_VCENTER && align&AT_LEFT)
		m_cl_btn.SetState(1);
	else if(align&AT_VCENTER && align&AT_CENTER)
		m_center_btn.SetState(1);
	else if(align&AT_VCENTER && align&AT_RIGHT)
		m_cr_btn.SetState(1);
	else if(align&AT_BOTTOM&& align&AT_LEFT)
		m_bl_btn.SetState(1);
	else if(align&AT_BOTTOM&& align&AT_CENTER)
		m_bc_btn.SetState(1);
	else if(align&AT_BOTTOM&& align&AT_RIGHT)
		m_br_btn.SetState(1);

}

void CTitleDlg::OnBnClickedUseEvenCheck()
{
	m_use_even_combo.EnableWindow(m_use_even_check.GetCheck());
	m_use_even_combo.SelectString(0,ID_STRING_EVEN);
	m_align&=01000777;
	SetCheck(m_align,false);
}

void CTitleDlg::OnCbnSelchangeUseEvenCombo()
{
	SetCheck(m_align,false);	
}
