// Dlg4Log.cpp : implementation file
//

#include "stdafx.h"
#include "resource.h"
#include "Dlg4Log.h"
#include "TransportSocketClient.h"

CDlg4Log *global_dlg = 0;
long dict_update_runned = 0;

// CDlg4Log dialog

IMPLEMENT_DYNAMIC(CDlg4Log, CaplResizableDialog)

CDlg4Log::CDlg4Log(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CDlg4Log::IDD, pParent)
	, m_Path2NewDict(_T(""))
{
	m_data = 0;
	m_StrOutput = _T("");
	m_autostart = false;
	m_event_run = CreateEvent(0,FALSE,FALSE,_T(""));
	InitializeCriticalSection(&m_protect_log);
}

CDlg4Log::~CDlg4Log()
{
	global_dlg = 0;
	DeleteCriticalSection(&m_protect_log);
}

void CDlg4Log::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_PATH2DICT, m_Path2NewDict);
	DDX_Control(pDX, IDC_LOG, m_CtrlOutput);
	DDX_Control(pDX, IDC_BTN_RUN, m_BtnRun);
	DDX_Control(pDX, IDC_EDIT_PATH2DICT, m_CtrlPath2Dict);
	DDX_Control(pDX, IDC_BTN_SELECT_DICT, m_BtnSelectDict);
	DDX_Control(pDX, IDCANCEL, m_CtrlCancel);
}


BEGIN_MESSAGE_MAP(CDlg4Log, CaplResizableDialog)
	ON_BN_CLICKED(IDCANCEL, &CDlg4Log::OnBnClickedCancel)
	ON_BN_CLICKED(IDC_BTN_SAVE, &CDlg4Log::OnBnClickedBtnSave)
	ON_BN_CLICKED(IDC_BTN_RUN, &CDlg4Log::OnBnClickedBtnRun)
	ON_BN_CLICKED(IDC_CLEAR, &CDlg4Log::OnBnClickedClear)
	ON_BN_CLICKED(IDC_BTN_SELECT_DICT, &CDlg4Log::OnBnClickedBtnSelectDict)
	ON_WM_TIMER()
END_MESSAGE_MAP()


// CDlg4Log message handlers

void CDlg4Log::OnBnClickedCancel()
{
	// TODO: Add your control notification handler code here
	if(InterlockedExchangeAdd(&dict_update_runned,0)==1)
	{
		m_data->m_AplTransport->SetBreak(true);
	}
	else
	{
		OnCancel();
	}
}

void CDlg4Log::OnBnClickedBtnSave()
{
	// TODO: Add your control notification handler code here
	CString name_file;
	//CString log_content;
	CFileDialog* dlg;
	LPCTSTR filter= APL_T("Лог-файл (*.log)|*.log||");
	dlg=new CFileDialog(FALSE,_T("log"),
		NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
		filter,this);

	if(dlg->DoModal() == IDCANCEL)
	{
		delete dlg;
		return;
	};
	name_file = dlg->GetPathName();
	delete dlg;
	if(name_file != _T(""))
	{
		FILE* outfile = _fopen(LPCTSTR(name_file), _T("w"));
		//		fwrite(LPCTSTR(m_StrOutput),(m_StrOutput.GetLength()),1,outfile);
		//m_CtrlOutput.GetWindowText(log_content);
		fwrite(LPCTSTR(m_StrOutput),(m_StrOutput.GetLength()), 1, outfile);
		fclose(outfile);
	}
}

void CDlg4Log::OnBnClickedBtnRun()
{
	// TODO: Add your control notification handler code here
	if(m_data == 0) return;

	UpdateData(TRUE);
	
	m_BtnRun.EnableWindow(FALSE);
	m_CtrlPath2Dict.EnableWindow(FALSE);
	m_BtnSelectDict.EnableWindow(FALSE);
	//m_CtrlCancel.SetWindowText(APL_T("Прервать"));
	m_CtrlCancel.EnableWindow(FALSE);


	LONG l = 0;
	HKEY key = 0;
	l = RegCreateKey(HKEY_CURRENT_USER,REG_KEY,&key);
	if(l == 0)
	{
		RegSetValueEx(key,_T("Dict4UpadteBD"), 0, REG_SZ, (BYTE*)(LPCTSTR)m_Path2NewDict, m_Path2NewDict.GetLength()*sizeof(TCHAR));
		RegCloseKey(key);
	}

	InterlockedExchange(&dict_update_runned, 1);
	SetEvent(m_event_run);
}

bool _ApplicationLevelLogMessageDlg(LPCTSTR message)
{
	if(global_dlg != 0)
	{
		global_dlg->LogMessage(message);
		return true;
	}
	return false;
}

BOOL CDlg4Log::OnInitDialog()
{
	CaplResizableDialog::OnInitDialog();

	AddAnchor(IDC_EDIT_PATH2DICT,TOP_LEFT,TOP_RIGHT);
	AddAnchor(IDC_BTN_SELECT_DICT,TOP_RIGHT,TOP_RIGHT);

	AddAnchor(IDC_LOG,TOP_LEFT,BOTTOM_RIGHT);

	AddAnchor(IDC_BTN_SAVE,BOTTOM_LEFT,BOTTOM_LEFT);
	AddAnchor(IDC_CLEAR,BOTTOM_LEFT,BOTTOM_LEFT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT,BOTTOM_RIGHT);

	// TODO:  Add extra initialization here
	if(m_data == 0) return FALSE;

	// предотвращаем потерю модальности после диалога с бочками из aplSocketTransport
	CORRECT_LOOSE_MODAL_ON_CLASS(m_data);

	global_dlg = this;

	m_CtrlOutput.SetLimitText(0xFFFFFFFF);

	m_data->m_AplTransport->SetApplicationLevelLogMessage(_ApplicationLevelLogMessageDlg);

	SetTimer(TIMER_ID,500,0);

	if(m_Path2NewDict == _T(""))
	{
		LONG l = 0;
		HKEY key = 0;
		l = RegCreateKey(HKEY_CURRENT_USER, REG_KEY, &key);
		if(l == 0)
		{
			unsigned long format = 0, size = MAX_PATH;
			TCHAR *buf = new TCHAR[size];

			// чтение списка использованных прокси для протокола http
			if(RegQueryValueEx(key, _T("LastProxyList"), 0, &format, (BYTE*) buf, &size)== 0 && size>0)
			{
				m_Path2NewDict = buf;
			}
			delete[] buf;
			l=RegCloseKey(key);
		}
	}

	if(m_autostart) OnBnClickedBtnRun();

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

void CDlg4Log::LogMessage(LPCTSTR message)
{
	EnterCriticalSection(&m_protect_log);
	m_new_mess += message;
	LeaveCriticalSection(&m_protect_log);
}

void CDlg4Log::LogMessageInt()
{
	int len;
// 	long nStartChar;
// 	long nEndChar;
	int nStartChar;
	int nEndChar;
// 	long first_visible;
	CString message;

	EnterCriticalSection(&m_protect_log);
	message += m_new_mess;
	m_new_mess = _T("");
	LeaveCriticalSection(&m_protect_log);
	if(message == _T("")) return;

	len = m_StrOutput.GetLength();

	// определяем текущее выделение
	m_CtrlOutput.GetSel(nStartChar, nEndChar);
	
	// чтобы манипуляции не были видны - убираем отображение
	m_CtrlOutput.SetRedraw(FALSE);

	// выделяем конец текста и добавляем к нему новый текст
	m_CtrlOutput.SetSel(len, len);
	m_CtrlOutput.ReplaceSel(message);

	// добавляем новый текст к внутренней переменной с текстом
	m_StrOutput += message;
	
	if(len-nEndChar > 3)
	{
		// Курсор был не в конце списка, так что восстанавливаем прежнее выделение
		m_CtrlOutput.SetSel(nStartChar, nEndChar);
	}
	else
	{
		// курсор был в конце - проматываем до нового конца текста
		len = m_CtrlOutput.GetLineCount();
		m_CtrlOutput.LineScroll(len);
	}
	// восстанавливаем перереисовку и перерерисовываем поле
	m_CtrlOutput.SetRedraw(TRUE);
	m_CtrlOutput.RedrawWindow();

}
void CDlg4Log::OnBnClickedClear()
{
	// TODO: Add your control notification handler code here
	m_StrOutput.Empty();
	m_CtrlOutput.SetWindowText(_T(""));
}

void CDlg4Log::OnBnClickedBtnSelectDict()
{
	// TODO: Add your control notification handler code here
	CFileDialog* dlg;
	LPCTSTR filter = APL_T("Файл словаря (*.dict)|*.dict||");

	UpdateData(TRUE);

	dlg = new CFileDialog(TRUE, _T("dict"),
		m_Path2NewDict, OFN_FILEMUSTEXIST |OFN_ENABLESIZING|OFN_EXPLORER,
		filter, 0);
	if(dlg->DoModal() == IDCANCEL)
	{
		delete dlg;
		return ;
	};
	m_Path2NewDict = dlg->GetPathName();

	UpdateData(FALSE);

}

void CDlg4Log::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default
	
	if(nIDEvent == TIMER_ID)
	{
		LogMessageInt();
		if(InterlockedExchangeAdd(&dict_update_runned,0) == 0)
		{
			m_BtnRun.EnableWindow(TRUE);
			m_CtrlPath2Dict.EnableWindow(TRUE);
			m_BtnSelectDict.EnableWindow(TRUE);
			//m_CtrlCancel.SetWindowText(APL_T("Выход"));
			m_CtrlCancel.EnableWindow(TRUE);
		}
	}

	CaplResizableDialog::OnTimer(nIDEvent);
}
