#include "CDiary.h"
#include "resource.h"
#include "CMainEditor.h"

IMPLEMENT_DYNAMIC(CDiary, CDialog)

BEGIN_MESSAGE_MAP(CDiary, CDialog)
	ON_EN_CHANGE(IDC_EDIT_DIARY, &CDiary::OnEnChangeEditDiary)
	ON_COMMAND(ID_SAVE_DIARY, &CDiary::OnSaveDiary)
END_MESSAGE_MAP()

CDiary::CDiary(CWnd* pParent)
	: CDialog(IDD_CMAINEDITOR_DIARY, pParent)
{
}

CDiary::~CDiary()
{
}

void CDiary::UpdateWindowTitle()
{
	if (CheckSaved())
	{
		CString str;
		str.Format(L"%d年%d月%d日", year, month, day);
		SetWindowTextW(str.GetString());
	}
	else
	{
		CString str;
		str.Format(L"%d年%d月%d日(未保存)", year, month, day);
		SetWindowTextW(str.GetString());
	}
}

bool CDiary::CheckSaved()
{
	CString text;
	edit_diary.GetWindowTextW(text);
	return diary_saved == text;
}

void CDiary::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT_DIARY, edit_diary);
}

BOOL CDiary::OnInitDialog()
{
	CDialog::OnInitDialog();
	//载入快捷键
	LOADHOTKEY(IDR_ACC_DIARY);

	CString str;
	str.Format(L"%d年%d月%d日", year, month, day);
	SetWindowTextW(str.GetString());
	//从数据库读取日记
	CMainEditor* mainEditor = (CMainEditor*)pMainEditor;
	CString dateValue;
	dateValue.Format(L"%d-%d-%d", year, month, day);
	diary_saved = mainEditor->GetDBFieldValue(DBTABLENAME_CALENDAR, L"date", dateValue.GetString(), L"diary");
	edit_diary.SetWindowTextW(diary_saved.GetString());
	return 0;
}

void CDiary::OnEnChangeEditDiary()
{
	// TODO:  如果该控件是 RICHEDIT 控件，它将不
	// 发送此通知，除非重写 CDialog::OnInitDialog()
	// 函数并调用 CRichEditCtrl().SetEventMask()，
	// 同时将 ENM_CHANGE 标志“或”运算到掩码中。

	UpdateWindowTitle();
}


void CDiary::OnSaveDiary()
{
	//保存数据到数据库
	CMainEditor* mainEditor = (CMainEditor*)pMainEditor;
	edit_diary.GetWindowTextW(diary_saved);
	CString dateValue;
	dateValue.Format(L"%d-%d-%d", year, month, day);
	if (diary_saved.GetLength() > 0)
		mainEditor->SetDBFieldValue(DBTABLENAME_CALENDAR, L"date", dateValue.GetString(), L"diary", diary_saved.GetString());
	else
		mainEditor->DelDBField(DBTABLENAME_CALENDAR, L"date", dateValue.GetString());
	UpdateWindowTitle();
	mainEditor->UpdateDisplayDiary();
	mainEditor->UpdateWindowTitle();
	mainEditor->Draw();
}

BOOL CDiary::PreTranslateMessage(MSG* pMsg)
{
	HOTKEYPROC;
}