// FileEditDlg.cpp : implementation file
//

#include "stdafx.h"
#include "dashboard.h"
#include <fstream>
#include "FileEditDlg.h"
#include "FileManagerDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CFileEditDlg dialog


CFileEditDlg::CFileEditDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CFileEditDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CFileEditDlg)
	m_Text = _T("");
	//}}AFX_DATA_INIT
}

void CFileEditDlg::SetFileName(char *filename)
{
	strcpy(m_FileName,filename);
}

void CFileEditDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFileEditDlg)
	DDX_Control(pDX, IDC_FILEEDIT, m_TextControl);
	DDX_Text(pDX, IDC_FILEEDIT, m_Text);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CFileEditDlg, CDialog)
	//{{AFX_MSG_MAP(CFileEditDlg)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFileEditDlg message handlers

BOOL CFileEditDlg::OnInitDialog()
{
	BOOL val = CDialog::OnInitDialog();
	SetWindowText(m_FileName);
	LoadFile();
	return val;
}

void CFileEditDlg::OnOK() 
{
	// TODO: Add extra validation here
	FlushFile();
	m_fm->DeleteFileEdit();
}

void CFileEditDlg::LoadFile() 
{
	char lineBuffer[256];
	
	fstream missionFile;
	missionFile.open(m_FileName ,ios::in); 

	m_Text = "";
	while (missionFile.eof() != 1) {
		missionFile.getline(lineBuffer, 256);
		m_Text += lineBuffer;
	    m_Text += "\r\n";
	}
	UpdateData(FALSE);
	missionFile.close();
}

void CFileEditDlg::FlushFile() 
{	
	if (!(m_TextControl.GetModify())) return;

	UpdateData(TRUE);

	int t = m_Text.Remove('\r');

	TRACE("Replaced %d carriage returns\n",t);

	if (strlen(m_FileName) > 0) {
		fstream missionFile;
		missionFile.open(m_FileName, ios::out);	
		missionFile.write(m_Text.GetBuffer(0), m_Text.GetLength());
		missionFile.close();
	}
	m_Text = "";
	UpdateData(FALSE);
}

void CFileEditDlg::OnCancel() 
{
	m_fm->DeleteFileEdit();
}

BOOL CFileEditDlg::PreTranslateMessage(MSG* pMsg)
{
 if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_TAB))
 {
  // get the char index of the caret position
  int nPos = LOWORD(m_TextControl.CharFromPos(m_TextControl.GetCaretPos()));
 
  // select zero chars
  m_TextControl.SetSel(nPos, nPos);
 
  // then replace that selection with a TAB
  m_TextControl.ReplaceSel("     ", TRUE);   // no need to do a msg translation, so quit.
  // that way no further processing gets done
  return TRUE;
 }  //just let other massages to work normally
 return CDialog::PreTranslateMessage(pMsg);
}