// wgscmapsDlg.cpp : implementation file
//

#include "stdafx.h"
#include "gcommlib.h"
#include "wgscmaps.h"
#include "wgscmapsDlg.h"
#include "cmaps.h"
#include "AreYouSure.h"

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

BOOL dontHide = FALSE;

/////////////////////////////////////////////////////////////////////////////
// CWgscmapsDlg dialog

CWgscmapsDlg::CWgscmapsDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CWgscmapsDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CWgscmapsDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
     m_fileNo = 0;
     m_done = FALSE;
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

     m_totalBytesToCompress = m_bytesCompressed = 0;
}

void CWgscmapsDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CWgscmapsDlg)
	DDX_Control(pDX, IDC_PERCENT, m_percent);
	DDX_Control(pDX, IDC_PROGRESS1, m_progress);
	DDX_Control(pDX, IDC_FNAME, m_fname);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CWgscmapsDlg, CDialog)
	//{{AFX_MSG_MAP(CWgscmapsDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_CANCELOP, OnCancelop)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CWgscmapsDlg message handlers

BOOL CWgscmapsDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CWgscmapsDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CWgscmapsDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CWgscmapsDlg::EndApp()
{
     ::PostQuitMessage( 0 );
}


BOOL CWgscmapsDlg::Done()
{
     if (! m_thread.Complete())
     {
          Sleep( 50 );
          return( FALSE );
     }

     if ((m_tempName.GetLength() > 0) && (m_finalName.GetLength() > 0))
     {
          CString   msg;
          unlink( m_finalName );

          int       renRes = -1;
          int       tries = 0;

          do
          {
               renRes = rename( m_tempName, m_finalName );

               if (renRes != 0)
               {
                    Sleep( 40 );
               }

               ++tries;
          } while ((renRes != 0) && (tries < 5));

          if (renRes != 0)
          {
               msg = "Failed to move " + m_tempName + " to " + m_finalName;
//               MessageBox( msg, "WGSCMAPS", MB_OK | MB_APPLMODAL );
          }
          //else
          //{
          //     msg = "Moved " + m_tempName + " to " + m_finalName;
         // }


          m_tempName.Empty();
          m_finalName.Empty();
     }

     if ((m_fileNo >= (int)nlogd) || m_done)
     {
          m_thread.KillConsole();
          m_done = TRUE;
          return( TRUE );
     }

     if (m_totalBytesToCompress <= 0)
     {
          for ( int count = 0; count < nlogd; ++count )
          {
               m_totalBytesToCompress += clog[ count ]->size;
          }
     }

     CString   fn = clog[m_fileNo]->path;

     if (fn.GetLength() > 0)
     {
          fn += '\\';
     }

     fn += clog[m_fileNo]->name;

     m_fname.SetWindowText( fn );

     int pct = (m_bytesCompressed * 100) / m_totalBytesToCompress;
     CString   caption;
     caption.Format( "%i%%", pct );
     m_percent.SetWindowText( caption );

     m_progress.SetPos( pct );

     UpdateWindow();

     StartApp( clog[ m_fileNo ]->path, clog[ m_fileNo ]->name );

     m_bytesCompressed += clog[ m_fileNo ]->size;

     ASSERT( m_bytesCompressed <= m_totalBytesToCompress );

     ++m_fileNo;

     return( FALSE );
}


void CWgscmapsDlg::StartApp( const CString &path, const CString &name )
{
     Cffblk fb;
     static GBOOL exists=FALSE;

     if (!exists) {
          if (!fnd1st(&fb,"WGSMSCOM.EXE",0)) {
               catastro("WGSCMAPS: WGSMSCOM.EXE NOT IN CURRENT DIRECTORY");
          }
          exists=TRUE;
     }

     CString   cmdStr;
     cmdStr.Format( "wgsmscom.exe /r %s\\%s", (const char *)path, (const char *)name );

     CString   cfl = compfil( name );

     mkdir( path + "\\COMPRESS" );

     m_thread.StartApp( cmdStr, ! dontHide );

     m_tempName = path + "\\" + cfl;
     m_finalName = path + "\\COMPRESS\\" + cfl;
}

void CWgscmapsDlg::OnClose() 
{
	if (m_done)
     {
     	CDialog::OnClose();
     }
}

void CWgscmapsDlg::OnCancelop() 
{
     BOOL      okToStop = FALSE;

     AreYouSure ays;

     ays.SetExplanation( "Canceling at this point will cause the compression "
                         "program to abort without proper cleanup.  This may result in "
                         "damaged or incomplete compressed files."
                       );

     BOOL      sure = ays.Confirm();

     if (sure)
     {
          okToStop = m_thread.Complete() || m_thread.Cancel();

          if (! okToStop)
          {
               MessageBox( "Unable to stop the current process", "Client App Compressor",
                           MB_OK | MB_ICONSTOP | MB_APPLMODAL
                         );
          }
     }
	
     if (okToStop)
     {
          m_done = TRUE;
          OnClose();
     }
}

BOOL CWgscmapsDlg::PreTranslateMessage(MSG* pMsg) 
{
	if ((pMsg->message == WM_CHAR) || (pMsg->message == WM_KEYDOWN)) 
     {
          if (pMsg->wParam == VK_ESCAPE)
          {
               //   OnCancelop();
               return( TRUE );
          }
     }
	
	return CDialog::PreTranslateMessage(pMsg);
}

CWgscmapsDlg::~CWgscmapsDlg()
{
     ClearClog();
}

