
#include "isam.h"
#include "winboss.h"                    /* windows header file */
#include "tools.cfg"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

char   *enlarge_buf (
					 char	*buf,
					 int	len);
void   printrec (
					 char	**fields,
					 FILE	*output,char type );
int    datecmp (
		char *,
		char *);
void   cnvtdate (
		char *,
		struct dt *);


struct dt {
		int    mo;
		int    dy;
		int    yr;
		};

static struct db {			/* record layout */
  char	date[10];			/* date string */
  int	   month,day,year; 		/* date numerics */
  char	date1[10];			/* time string */
  int	   mnth1,day1,yr1; 		/* time numerics */
  char	invent[3]; 			/* inventory report */
  char	purch[3];				/* purchases report */
  char	sales[3];				/* sales report */
  char	all[3];				/* all years */
  char	current[3];			/* current year */
  char	out_file[10];			/* file name if file */
  char	age[6]; 			/* prior year for prior year report */
  int	old;				/* age numeric */
} rec;



WINDOWPTR wn;				/* window pointer */
WIFORM    frm;				/* form pointer */
char      lmonth[5];
long      total;
int       lines;
char      type_sort;    /* sort types */
int       patrib, uatrib;


void  print_heading(FILE *,char);
void  print_invent(void);
void  print_db ( Db_Obj     *db,  Index_Obj  *index);


void print_func (ch)
int ch;
{
char   * emsg1,*emsg2,*emsg3;		/* error msg ptr */
char     fchar;				/* fill character */

   switch (ch)
      {
      case 1:
         rec.invent [0] = 'x';
         break;

      case 2:
         rec.purch [0] = 'x';
         break;

      case 3:
         rec.sales [0] = 'x';
         break;

      case 4:
         rec.current [0] = 'x';
         break;

      case 5:
         rec.all [0] = 'x';
         break;

      case 99:
         return;
         break;

      }
   
   wn = wn_open(0,5,10,45,13, patrib, uatrib);
   if(!(wn))
      {				/* errors ?? */
      printf("wn_open failed!!\n");       /* tell of woe... */
      return;				/* and die */
      }


   wn_title(wn," Inventory Print Options ");

  frm = wn_frmopn (4);
  if(!frm) {				/* errors ?? */
    printf("wn_frmopn failed!!\n");     /* tell of woe... */
    return;
  }


  emsg1 = "Invalid date, press any key to continue...";
  emsg2 = "Invalid time, press any key to continue...";
  emsg3 = "Prior year must be between 1900 and 2050...";

  fchar = '_';
  wn_gdate (SET,frm,0, wn,4,1, "Period Beginning Date: ",patrib,fchar,&rec.month,&rec.day,&rec.year,rec.date,NSTR,emsg1);
  wn_gdate (SET,frm,1, wn,5,1, "Period Ending Date:    ",patrib,fchar,&rec.mnth1,&rec.day1,&rec.yr1, rec.date1,NSTR,emsg1);
  wn_gtext (SET,frm,2, wn,7,1, "Output file name: ",patrib,fchar,8,rec.out_file,NSTR,NSTR);

  if(!wn_frmget(frm)) { 		/* get (read) form */
    v_cls(7);				/* die if errors !! */
    v_locate(0,0,0);
    printf("Memory Corruption Error!\n");
    return;
  }

  wn_clr(wn);
  wn_close(wn); 			/* close window */
  print_invent();

  wn_printf(wn,"\nPress any key to continue..");
  v_getch();

  wn_frmcls(frm);			/* close for */
  wn_close(wn); 			/* close window */

  return; 			

}

/*********************	  print_invent	  ********************/

void  print_invent(void)

{
	int	c;
	Db_Obj	*db;
	Index_Obj *index;
	FILE	*output;
   WINDOWPTR wn;			   /* window pointer */
   int pagecnt = 1;
   int linecnt = 0;

   wn = wn_open(0,5,10,45,13,patrib, uatrib);
   wn_printf(wn,"Outfile is: %s\n", rec.out_file);
	db = iopen_db ("\\gun\\db\\INVENT");
	if (db == NULL)
      {
		iprterr ();
      iclose_db (db);
		return;
      }

	index = ihandle (db, "PURCH");
	if (index == NULL)
      {
		iprterr ();
      iclose_db (db);
		return;
      }

	for (;;)
      {
      wn_printf (wn,"\r\nMake sure your Printer is online");
	   wn_printf (wn,"\r\nPress Return to print to Printer:");
	   wn_printf (wn,"\r\nSpace to print to stdout:");
      wn_printf (wn,"\r\nEsc to exit:");
      c = getch ();
      if (c == 0x1b)
         {
         iclose_db (db);
//       wn_close(wn); 			/* close window */
			return;
         }
      else if (c == '\r' || c == '\n')
         {
         if ((output = fopen ("prn", "a")) == NULL)
            {
            wn_printf (wn,"\r\nCan't open printer device\n");
            iclose_db (db);
				return;
            }

         wn_printf (wn,"\r\n\r\nPrinting");
			break;
         }
      else if ((c == ' ') && (rec.out_file [0] != ' '))
         {
         if ((output = fopen(rec.out_file, "w+")) == NULL)
            {
            wn_printf(wn,"\r\nCan't open %s.prn",rec.out_file);
            iclose_db (db);
            return;
            }

         wn_printf (wn,"\r\nPRINTING to file %s",rec.out_file);
         break;
         }
      }

   print_db(db, output);

   iclose_db (db);

   fprintf (output, "\f");
   fclose (output);
	return;
} 

/******************************************************************************
   print_db - print database in index order

   Returns no value, but prints to output file
******************************************************************************/




void   print_db (db, output)
Db_Obj   *db;      /* print this database */
FILE   *output;   /* to this output file */
{
   int   status;    /* status from isam functions */
   char   **fields;   /* points to fields in record */
   int   nfields;   /* number of fields per record */
   int   buflen;    /* length of record buffer */
   char   *buf;      /* record buffer */
   char   *newbuf;   /* points to larger record buffer */
   Rec_Len reclen;    /* length of record */
   Index_Obj *index;   /* in order of this index */
   int   use_sd, use_ed, pastend, datesub;        /* counter */
   char    sdate[10];
   char    edate[10];
   char *key[2];
   int linecnt = 0;
   char    rdate[9];

   lmonth[0] = '\0';
   nfields = igetfldcount (db);
   fields = (char **) malloc (
      (nfields + 1 /* for NULL */) * sizeof (char *));
   if (fields == NULL) {
      cprintf ("Can't allocate memory\n");
      return;
   }

   buflen = 0;
   buf = NULL;


   type_sort = ' ';

   if(rec.invent[0] > ' ')
      {
      index = ihandle (db, "dateIDX");
      if (index == NULL)
         {
         iprterr ();
         return;
         }

      datesub = 7;
      type_sort = 'I';
      }

   if (rec.purch[0] > ' ')
      {
      index = ihandle (db, "dateIDX");
      if (index == NULL)
         {
         iprterr ();
         return;
         }

      datesub = 7;
      type_sort = 'P';
      }

   if(rec.sales[0] > ' ')
      {
      index = ihandle (db, "sdateIDX");
      if (index == NULL)
         {
         iprterr ();
         return;
         }

      datesub = 11;
      type_sort = 'S';
      }

   if(rec.current[0] > ' ')
      {
      index = ihandle (db, "dateIDX");
      if (index == NULL)
         {
         iprterr ();
         return;
         }

      datesub = 7;
      type_sort = 'C';
      }

   if (rec.all[0] > ' ')
      {
      index = ihandle (db, "makrIDX");
      if (index == NULL)
         {
         iprterr ();
         return;
         }

      datesub = 7;
      type_sort = 'M';
      }

   if (type_sort == ' ')
      return;
   else
      print_heading(output,type_sort);

   if (type_sort != 'M' && rec.month && rec.day && rec.year)
      {
      sprintf(sdate, "%.02d/%.02d/%.02d", rec.year, rec.month, rec.day);
      wn_printf(wn,"\r\n\r\nBegin date: %s", sdate);
      key[0] = sdate;
      key[1] = "";
      ifindkey(db, index, key);
      }
   else
      ifindhead(db, index);

   if (type_sort == 'M' && rec.month && rec.day && rec.year)
      {
      sprintf(sdate, "%.02d/%.02d/%.02d", rec.year, rec.month, rec.day);
      use_sd = TRUE;
      }
   else
      use_sd = FALSE;

   if (rec.mnth1 && rec.day1 && rec.yr1)
      {
      use_ed = TRUE;
      sprintf(edate, "%.02d/%.02d/%.02d", rec.yr1, rec.mnth1, rec.day1);
      wn_printf(wn,"\r\nEnd date:   %s\n", edate);
      }

   else use_ed = FALSE;


   buflen = 0;
   buf = NULL;

   for (status = OK,pastend = FALSE; status == OK && !pastend; status = ifindnext (db, index))
      {
      if (igetreclen (db, index, &reclen) == OK)
         {
         if (reclen > buflen)
            {
            newbuf = enlarge_buf (buf, reclen);
            if (newbuf == NULL)
               continue;

            buf = newbuf;
            buflen = reclen;
            }
         }
      else
         {
         iprterr ();
         return;
         }

      if (igetrec(db,index,fields,buf,buflen) == OK)   /* exists */
         {
         if (use_sd)
            if (strcmp(sdate, fields[datesub]) > 0)
               continue;
            
         if (use_ed)
            if (strcmp(edate, fields[datesub]) < 0)
               {
               if (type_sort != 'M')
                  pastend = TRUE;
               continue;
               }

         // reverse the date from the database
         if (fields[11][0] == '\0')
            rdate [0] = '\0';
         else
            {
            rdate[0] = fields[11][6];
            rdate[1] = fields[11][7];
            rdate[2] = fields[11][2];
            rdate[3] = fields[11][3];
            rdate[4] = fields[11][4];
            rdate[5] = fields[11][5];
            rdate[6] = fields[11][0];
            rdate[7] = fields[11][1];
            rdate[8] = 0;
            }

         // print inventory only if sales date does not exist or is after 
         // the ending date
         if (rec.invent[0] != 'x')
            printrec (fields, output, type_sort);
         else if ((rdate[0] == 0) || (strcmp (edate, rdate) < 0))
            printrec (fields, output, type_sort);

         } /* if get */
      else
         {
         iprterr();
         return;
         }
      }  /* end for each record in db -- for(status... */
   
   return;
   
} /* print_db */


/*
   enlarge_buf - realloc buffer to new size len

   Returns pointer to bigger buffer, or NULL if out of memory
*/

char   *enlarge_buf (buf, len)
char   *buf;      /* enlarge this buffer */
int   len;      /* to this size */
{
   if (buf == NULL)
      buf = malloc (len);
   else
      buf = realloc (buf, len);

   if (buf == NULL) {
      cprintf ("Can't allocate record buffer\n");
      return (NULL);
   }
   return (buf);
} /* enlarge_buf */
/*
   printrec - print record to output file

   Returns no value, but prints to output file
*/

void   printrec (fields, output,type)
char   **fields;      /* record to print */
FILE   *output;      /* to this output file */
char type;
{

   lines++;
   if (lines > 50)
      {
      fprintf (output, "\f");
      print_heading(output,type_sort);
      lines = 1;
      }
      

if(lmonth[0] == '\0'&& type == 'C'){
    memcpy(lmonth,fields[7],5);
    total = 0l;
   }

 if(lmonth[0] &&  type == 'C'){
  if(memcmp(fields[7],lmonth,5))
    {
    fprintf(output,"       ----------------------------------------------------------------------------------------------------\n");
    fprintf(output,"       TOTAL FOR %.5s %*c %8ld\n\n",lmonth,58,' ',total);
    memcpy(lmonth,fields[7],5);
    total =atol(fields[9]);
     }
   else
    total +=atol(fields[9]);
   }
 fprintf(output,"  %*c%-5.5s    %-10.10s    %-20.20s    %-4.4s    %-8.8s    %-8.8s    %-7.7s    %-15.15s\n",
     5,' ',
      fields[0], 
      fields[1], 
      fields[2], 
      fields[3], 
      fields[4], 
      fields[7], 
      fields[9], 
      fields[11]);
   return;
} /* printrec */

/* end prlabels.c */



void print_heading(outfile,h_type)
 FILE        *outfile;
 char        h_type;
 {
  char report_title[25];
  switch(h_type){
   case 'I':
     strcpy(report_title,"    INVENTORY  ");
     break;
   case 'P':
     strcpy(report_title,"    PURCHASES  ");
     break;
   case 'S':
     strcpy(report_title,"    SALES  ");
     break;
    case 'C':
     strcpy(report_title,"   MONTHLY SUMMARY ");
     break;
    case 'M':
     strcpy(report_title,"    MANUFACTURER  ");
     break;
   default:
     strcpy(report_title,"      ");
     break;
    }
fprintf(outfile,"%c",0x0f);           /* compressed print*/
fprintf(outfile,"\n%*c Period Beginning Date: %02d/%02d/%02d %*c\n",
          5,' ',rec.month,rec.day,rec.year,100,' ');
fprintf(outfile,"%*c Period Ending Date   : %02d/%02d/%02d \n",
          5,' ',rec.mnth1,rec.day1,rec.yr1);


// fprintf(outfile,"$FORM SPSLND;\n");   /*    landscape     */
 fprintf(outfile,"%c",0x0f);           /* compressed print*/
 fprintf(outfile,"\n%*c%c%c%c%s%c%c%c\n\n\n",
          40,' ', 0x0e,0x1b,0x45,report_title,0x1b,0x46,0x14);
 fprintf(outfile,"  %*c%-5.5s    %-10.10s    %-20.20s    %-4.4s    %-8.8s    %-8.8s    %-7.7s    %-15.15s\n",
          5,' ',  "STK #", "MAKER","MODEL", "YEAR", "SERIAL #", "PUR DATE", "COST", "DATE","SALES PR");
 fprintf(outfile,"\n\n");
 }
