#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
#include <sys\types.h>
#include <sys\stat.h>

#include "window.h"
#include "cardfile.h"


int CardFileOpen(szFileName, iCmd)
  char *szFileName;
  int  iCmd;
{
  int  fd;
  int  nRec;
  char szFile[80];
  CARDFILE tmpCardFile;
  char *szBuf;

  strcpy(szFile, szFileName);
  if (!strchr(szFile, '.'))
    strcat(szFile, ".CRD");

  if ((fd = open(szFile, O_RDONLY | O_BINARY)) < 0)
  {
    MessageBox("Can't open the file", szFile, NULL, "Error", MB_OK);
    return FALSE;
  }
  if (read(fd, (char *) &tmpCardFile, sizeof(tmpCardFile)) != sizeof(tmpCardFile) ||
      tmpCardFile.nMagicCookie != MAGIC_COOKIE)
  {
    MessageBox("Bad Header in file", szFile, NULL, "Error", MB_OK);
    close(fd);
    return FALSE;
  }

  if (iCmd == ID_OPEN)
    strcpy(szCurrFileName, szFile);

  for (nRec = tmpCardFile.nRecords;  nRec > 0;  nRec--)
  {
    RECORD *pRec;
    pRec = (RECORD *) emalloc(sizeof(RECORD));

    read(fd, (char *) pRec, sizeof(RECORD));
    ListAdd(&CurrRecordList, ListCreate((char *) pRec));
    CurrCardFile.nRecords++;

    pRec->hWnd = hCurrCard =
         CreateWindow("Card",          /* class */
                       NULL,           /* title */
                       0L,
                       1+nRec,(VideoInfo.length-11)-(nRec*2), 50,10,
                       SYSTEM_COLOR,   /* attr */
                       0,              /* id */
                       hWndCardfile,   /* hParent */
                       NULLHWND,       /* hMenu */
                       0,              /* hInst */
                       0L);            /* lpParam */
     SetWindowText(GetWindowWord(pRec->hWnd, GWW_HWNDINDEX), pRec->szIndex);

     if (iCmd == ID_MERGE)
     {
       CardAlphabetize(CurrCardFile.nRecords-1);
     }
  }

  szBuf = emalloc(4096);

  for (nRec = 0;  nRec < tmpCardFile.nRecords;  nRec++)
  {
    RECORD *pRec;
    pRec = (RECORD *) ListGetNth(CurrRecordList, nRec)->data;
    lseek(fd, pRec->ulSeekPos, 0);
    if (read(fd, szBuf, pRec->nChars) == pRec->nChars)
    {
      szBuf[pRec->nChars] = '\0';
      SetWindowText(GetWindowWord(pRec->hWnd, GWW_HWNDEDIT), szBuf);
    }
  }

  MyFree(szBuf);

  close(fd);

  CardFileAdjustWindows();
  return TRUE;
}


int CardFileMaybeSave(iCmd)
  int iCmd;
{
  int rc;

  if (CurrCardFile.nRecords > 0)
  {
    if (iCmd == ID_SAVE)
      rc = IDYES;
    else
      rc = MessageBox("Save existing cardfile?", NULL,NULL,NULL, MB_YESNOCANCEL);
    if (rc == IDCANCEL)
      return FALSE;
    else if (rc == IDNO)
      return TRUE;
    else
    {
      if (szCurrFileName[0])
      {
        CardFileSave(szCurrFileName);
      }
      else
      {
        rc = GenericDialogDriver(ID_SAVE, SaveFileDialogProc);
        if (rc == IDOK)
          CardFileSave(szCurrFileName);
      }
      return TRUE;
    }
  }
  else
    return TRUE;
}


int CardFileSave(szFileName)
  char *szFileName;
{
  int fd;
  int nRecs;
  char *szBuf;

  if ((fd = open(szFileName, O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, 
                             S_IREAD | S_IWRITE)) < 0)
  {
    MessageBox("Can't open the file", szFileName, NULL, "Error", MB_OK);
    return FALSE;
  }

  CardFileCalcSeekPositions();

  CurrCardFile.nMagicCookie = MAGIC_COOKIE;
  write(fd, (char *) &CurrCardFile, sizeof(CurrCardFile));

  for (nRecs = 0;  nRecs < CurrCardFile.nRecords;  nRecs++)
  {
    RECORD *pRec = (RECORD *) ListGetNth(CurrRecordList, nRecs)->data;
    write(fd, (char *) pRec, sizeof(RECORD));
  }

  szBuf = emalloc(4096);
  for (nRecs = 0;  nRecs < CurrCardFile.nRecords;  nRecs++)
  {
    RECORD *pRec = (RECORD *) ListGetNth(CurrRecordList, nRecs)->data;
    GetWindowText(GetWindowWord(pRec->hWnd, GWW_HWNDEDIT), szBuf, 4096);
    write(fd, szBuf, pRec->nChars);
  }
  MyFree(szBuf);

  close(fd);
}


int CardFileCalcSeekPositions()
{
  int nRecs;
  DWORD ulSeekPos;

  ulSeekPos = sizeof(CARDFILE) + (CurrCardFile.nRecords * sizeof(RECORD));

  for (nRecs = 0;  nRecs < CurrCardFile.nRecords;  nRecs++)
  {
    RECORD *pRec = (RECORD *) ListGetNth(CurrRecordList, nRecs)->data;
    pRec->nChars = 
     SendMessage(GetWindowWord(pRec->hWnd,GWW_HWNDEDIT),WM_GETTEXTLENGTH,0,0L);
    pRec->ulSeekPos = ulSeekPos;
    ulSeekPos += pRec->nChars;
  }

  return TRUE;
}


extern FILE *PrinterOpen();

CardFilePrint()
{
  int  iRec;
  FILE *fpPrn;

  if ((fpPrn = PrinterOpen()) == NULL)
    return FALSE;

  for (iRec = 0;  iRec < CurrCardFile.nRecords;  iRec++)
  {
    CardPrint(iRec, fpPrn);
  }

  fclose(fpPrn);
  return TRUE;
}


CardPrint(iRec, fpPrn)
  int  iRec;
  FILE *fpPrn;
{
  BOOL bClosePrn = FALSE;
  char *szBuf;
  RECORD *pRec;

  if (!fpPrn)
  {
    if ((fpPrn = PrinterOpen()) == NULL)
      return FALSE;
    bClosePrn = TRUE;
  }

  if ((szBuf = emalloc(4096)) == NULL)
  {
    if (bClosePrn)
      fclose(fpPrn);
    return FALSE;
  }

  pRec = (RECORD *) ListGetNth(CurrRecordList, iRec)->data;

  /*
    Print the index header
  */
  fprintf(fpPrn, "%s\n", pRec->szIndex);

  /*
    Print the text
  */
  GetWindowText(GetWindowWord(pRec->hWnd, GWW_HWNDEDIT), szBuf, 4096);
  fprintf(fpPrn, "%s\n\n\n", szBuf);

  if (bClosePrn)
    fclose(fpPrn);
  if (szBuf)
    MyFree(szBuf);
  return TRUE;
}


FILE *PrinterOpen()
{
  FILE *fp;

  fp = fopen("prn", "w");
  return fp;
}
