// Copyright 1994-1997 by Jon Dart
// epdstat.cpp : EPD status dialog
//

#include "stdafx.h"
#include "epdstat.h"
#include "epdrec.h"
#include "chessio.h"
#include "globals.h"
#include <process.h>

#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// EpdStatusDialog dialog

static char tempfile[MAX_PATH];

EpdStatusDialog::EpdStatusDialog(CWnd* pParent, 
                                 CString &filename,
                                 ifstream &strm,
                                 Board &board,
                                 BOOL annotate)
        : CDialog(EpdStatusDialog::IDD, pParent),ifs(strm),
          current_board(board), parent((CArasanView*)pParent)
{
        //{{AFX_DATA_INIT(EpdStatusDialog)
        m_EpdID = "";
        m_EpdRecord = "1";
        //}}AFX_DATA_INIT
        // get just the name portion of the filename:
        char *p = filename.GetBuffer(filename.GetLength());
        char *q = p + filename.GetLength();
        while (q != p && *q != '\\' && *q != ':') --q;
        
        // show the user what file we're reading:
        AfxFormatString1(m_EpdFile,IDS_EPD_FILE,q == p ? p : q+1);
        filename.ReleaseBuffer();
        pathName = filename;
        running = cancelled = FALSE;
}

void EpdStatusDialog::DoDataExchange(CDataExchange* pDX)
{
        CDialog::DoDataExchange(pDX);
        //{{AFX_DATA_MAP(EpdStatusDialog)
        DDX_Text(pDX, ID_EPD_FILE, m_EpdFile);
        DDX_Text(pDX, ID_EPD_ID, m_EpdID);
        DDX_Text(pDX, ID_EPD_RECORD, m_EpdRecord);
        //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(EpdStatusDialog, CDialog)
        //{{AFX_MSG_MAP(EpdStatusDialog)
        ON_WM_SHOWWINDOW()
        //}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// EpdStatusDialog message handlers

void EpdStatusDialog::OnCancel()
{
    if (running)
    {
        parent->stop_search(FALSE);
        cancelled = TRUE;
    }
    else    
        CDialog::OnCancel();
}

// Thread procedure
static unsigned int _stdcall threadProc(LPVOID pParam)
{
    EpdStatusDialog *pDialog = (EpdStatusDialog*)pParam;
    EPD_Record *rec;
    DWORD count = 0;

    char path[MAX_PATH]; 
    GetTempPath(MAX_PATH,path);
    GetTempFileName(path,"Arasan", 0, tempfile);

    ofstream outfile;
    outfile.open(tempfile,ios::out | ios::trunc); 
    pDialog->running = TRUE;
    while (!pDialog->cancelled && 
        (rec = ChessIO::read_epd_record(pDialog->ifs,
                         pDialog->current_board)) != NULL)
    {
       if (rec->has_error())
       {
           if (pDialog->MessageBox(rec->get_error(),"Error",MB_OKCANCEL) == IDCANCEL)
               pDialog->cancelled = TRUE;
           delete rec;
           continue;
       }
       
       theView->draw_board();    
       theView->show_side(); 
       
       count++;
       if (rec->has_val("id"))
       { 
          CString idstr;
          rec->get_val("id",idstr);
          /**
          theLog->write("===  EPD record: ");
          theLog->write((LPCSTR)idstr);
          theLog->write(" read.");
          theLog->write_eol();
          ***/
          pDialog->m_EpdID = idstr;
       }
       char countstr[10];
       wsprintf(countstr,"%ld",count);
       pDialog->m_EpdRecord = countstr;
       pDialog->UpdateData(FALSE);
       game_moves->clear();
       pDialog->parent->computer_plays(pDialog->current_board.Side());
       ChessIO::annotate_epd_record(rec,pDialog->current_board,outfile);
       delete rec;
    }
    pDialog->current_board.Reset();
    pDialog->running = FALSE;
    outfile.close();
    pDialog->ifs.close();
    if (!pDialog->cancelled)
    {
        // copy temporary file onto input file, replacing it
        CFile newfile(pDialog->pathName,CFile::modeWrite);
        CFile readfile(tempfile,CFile::modeRead);
        const BUFSIZE = 4096;
        char *buf = new char[BUFSIZE];
        UINT nRead;
        while (nRead = readfile.Read(buf,BUFSIZE))
        {
            newfile.Write(buf,nRead);
        }
        delete [] buf;
    }
    // remove temporary file
    CFile::Remove(tempfile);
    // bring down the dialog
    ::SendMessage(pDialog->m_hWnd,WM_CLOSE,0,0L);
    return 0;
}

void EpdStatusDialog::OnShowWindow(BOOL bShow, UINT nStatus) 
{
    CDialog::OnShowWindow(bShow, nStatus);

    // Run the EPD file reading routine in a different thread.
    // This allows the GUI (including this dialog) to stay
    // "live" while the process runs.
    unsigned threadId;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL,0 /*stack*/,
        &threadProc,(void*)this, (DWORD)0,
        &threadId);

}
