#include <time.h>
#include <fcntl.h>
#include "system.h"
#include "defines.h"

extern long Time_connect, Time_menu_entry, Time_system, Time_remaining;

extern struct System System;

static short Last_Day, This_Day;

/***************************/
int Init_Stat()
{
struct tm *timestat;
int x, fd, stat, Size;
char *ptr, str[133];

Time_system=time(NULL);
timestat=localtime(&Time_system);
This_Day=timestat->tm_wday;
Last_Day=This_Day;

Size=(sizeof(struct Daily_Statistics)*7)+(sizeof(struct Overall_Statistics));
strcpy(str,System.Location);
strcat(str,"Tag.Stat");

fd=open(str,O_RDONLY);
if(fd==(-1))
	{
	fd=open(str,O_WRONLY+O_CREAT);
	if(fd==(-1)) { return(FAILURE); }
	for(x=0;x<Size;++x)
		{
		ptr=&System.Daily_Statistics[0].Time_Active;
		ptr+=x;
		*ptr='\000';
		}
	System.Overall_Statistics.Time_First_Online=Time_system;
	stat=write(fd,&System.Daily_Statistics[0].Time_Active,Size);
	stat=close(fd);
	Open_Day(This_Day);
	return(SUCCESS);
	}

stat=read(fd,&System.Daily_Statistics[0].Time_Active,Size);
stat=close(fd);
Open_Day(This_Day);
return(SUCCESS);
}

/***************************/
/* CLOSE_DAY() FINISHES ALL DAILY STATS FOR THE DAY */
int Close_Day(day)
	int day;
{
Save_Stat();
}

/***************************/
/* OPEN_DAY() INITIALIZES THE DAILY STAT FOR THE NEW DAY */
int Open_Day(day)
	int day;
{
System.Daily_Statistics[day].Time_Active=0L;
System.Daily_Statistics[day].Time_Fallow=0L;
System.Daily_Statistics[day].Guest_Calls=0;
System.Daily_Statistics[day].New_Calls=0;
System.Daily_Statistics[day].Valid_Calls=0;
System.Daily_Statistics[day].Messages_Written=0;
System.Daily_Statistics[day].Letters_Written=0;
System.Daily_Statistics[day].Files_Uploaded=0;
System.Daily_Statistics[day].Files_Downloaded=0;
System.Daily_Statistics[day].New_Accounts=0;
}

/***************************/
int Save_Stat()
{
return(SUCCESS);
}

/***************************/
/* CLOSE_STAT() IS USED DURING SHUTDOWN() */
int Close_Stat()
{
Append_Stat(STAT_SHUTDOWN);
Save_Stat();
}

/***************************/
/* APPEND_STAT() DOES THE STAT ADDITIONS FOR EACH EVENT */
int Append_Stat(which)
	int which;
{
return(SUCCESS);
}

/********************************/
int Report_Stat()
{
char string[133];

PutStr("System Statistics\r\n\r\n");

sprintf(string,"  System : %s\r\n",System.Name);
PutStr(string);

sprintf(string,"    Sysop: %s\r\n",System.Sysop);
PutStr(string);

sprintf(string,"First Day: %s\r\n\r\n",
	ctime(&System.Overall_Statistics.Time_First_Online));
PutStr(string);

PutStr("\r\n");
}
