#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>             /* for atoi() */

#include "global.h"
#include "custom.h"    /* for date formats */

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_news_util.h"
#include "manhat-lib/shared_access.h"

static void
read_parameters (char *course, char *key, char *sender, char *info_fname,
                   char *score, char *start_time, char *end_time,
                        char *exercise, char *orig_fname, 
                        char *system_fname, int *hidden)
{

  char hide[MAX_PATH + 1];


  cs_get_required_parameter ("crs", course, MAX_PATH);	/* shared_cgi_util.c */
  cs_get_required_parameter ("id", key, MAX_KEY);	/* shared_cgi_util.c */
  
  cs_get_required_parameter ("hide", hide, MAX_PATH);	/* shared_cgi_util.c */
  *hidden = atoi(hide); 

  cs_get_required_parameter ("sender", sender, MAX_USERNAME);	/* shared_cgi_util.c */
  cs_get_required_parameter ("info", info_fname, MAX_FILENAME);	/* shared_cgi_util.c */
  cs_get_required_parameter ("Score", score, MAX_HOTPOT_SCORE);	/* shared_cgi_util.c */
  cs_get_required_parameter ("Start_Time", start_time, MAX_HOTPOT_TIME);	/* shared_cgi_util.c */
  cs_get_required_parameter ("End_Time", end_time, MAX_HOTPOT_TIME);	/* shared_cgi_util.c */
  
  /* the title of the quiz may have been left blank */  
  cs_get_optional_parameter ("Exercise", exercise, MAX_HOTPOT_EXERCISE);	/* shared_cgi_util.c */
  if(strlen(exercise) ==0)
    strncpy(exercise, " ", MAX_HOTPOT_EXERCISE + 1);
  cs_get_required_parameter ("orig_fname",orig_fname,MAX_FILENAME);
  cs_get_required_parameter ("fname",system_fname,MAX_FILENAME);  
  

}


/*
** time string may look like this:
**    Wednesday, July 18, 2001 15:15:23
** or it may look like this:
**    7/18/2001 15:15:23
** depending on the browser that sent it
**
** Because of the inconsistent behavior
** of browsers we'll just extract the
** hour:min:second part from the end
**
** we're ultimately interested in the 
** differences between two times, although
** this will mess up when user starts a
** test on one day and ends it on another.
**
*/

static void
convert_time(char *time_string, time_t *converted)
{
 struct tm t;
 char *ptr, *ptr2;

/* if anything goes wrong, we'll return with this value */  
 *converted = 0;   
 
/* set date to January 1, 2000 */
 t.tm_mon = 1;
 t.tm_mday = 1;
 t.tm_year = 100;
 t.tm_isdst = 0;    

 /* now extract hour:min:sec from end */ 
 ptr = strrchr(time_string,':');
 if(!ptr)
    return;
 t.tm_sec = atoi(ptr+1);
 
 *ptr = '\0';
 ptr2 = strrchr(time_string,':');
 if(!ptr2)
  {
    *ptr = ':';
    return;
  }
 t.tm_min = atoi(ptr2 + 1);
 *ptr = ':';
 
 *ptr2 = '\0';
 ptr = strrchr(time_string,' ');
 if(!ptr)
  {
   *ptr2 = ':';
   return;
  }
 t.tm_hour = atoi(ptr + 1);
 *ptr2 = ':';

 /* convert to long value */ 
 *converted = mktime(&t);    
 }
        
     
     




static time_t
time_elapsed(char *start_time,
                  char *end_time)
{
time_t converted_start, converted_end;

 convert_time(start_time,&converted_start);
 convert_time(end_time, &converted_end);
 
 if(converted_end < converted_start)  /* then assume we crossed midnight */
    converted_end += (24 * 60 * 60);  /* add 24 hours */
 
 return (converted_end - converted_start);
 
}                  


static void
calculate_elapsed_time(time_t elapsed_time, 
			int *hours, int *minutes, int *seconds)
{
int remainder;
 
 *hours = elapsed_time / 3600;
 remainder = elapsed_time % 3600;
 
 *minutes = remainder / 60;
 *seconds = remainder % 60;
 
}
			




static void
show_results(char *score, char *exercise, 
			time_t elapsed_time, char *orig_fname, int hidden,
			time_t current_time)
{
 char timestring[MAX_TIMESTRING + 1];
 int hours, minutes, seconds;
 
 calculate_elapsed_time(elapsed_time, &hours, &minutes, &seconds);
 strftime (timestring, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT,
	    localtime (&current_time));
  
 cs_set_value("exercise",  exercise);
 cs_set_value("orig_fname",  orig_fname);
 cs_set_value("current_time", timestring); 
 cs_set_value("score", score); 

 snprintf(timestring, MAX_TIMESTRING +1, "%02d:%02d:%02d",hours, minutes,seconds);
 cs_set_value("elapsed_time", timestring); 
              

 if(hidden)
    cs_set_int_value("hidden", 1); 

}

 
static void
save_data(char *sender, char *info_fname, char *score,
            char *start_time, char *end_time, time_t elapsed_time, 
            char *exercise, char *orig_fname, char *system_fname, 
            int hidden,  time_t current_time,
            CONFIG_STRUCT *conf, SESSION *user)
{            
 HOTPOTATO_INFO_STRUCT data;
 char data_path[MAX_PATH + 1];
 FILE *fp;
 
 
 strncpy(data.sender,sender,MAX_USERNAME + 1);
 strncpy(data.info_fname, info_fname, MAX_FILENAME + 1);
 strncpy(data.score, score, MAX_HOTPOT_SCORE + 1);
 strncpy(data.start_time, start_time, MAX_HOTPOT_TIME + 1);
 strncpy(data.end_time, end_time, MAX_HOTPOT_TIME + 1);
 strncpy(data.exercise, exercise, MAX_HOTPOT_EXERCISE + 1);
 strncpy(data.orig_fname,orig_fname,MAX_FILENAME + 1);
 strncpy(data.system_fname,system_fname,MAX_FILENAME + 1);
 
 data.time_submitted = current_time;
 data.elapsed_time = elapsed_time;
 data.hidden = hidden;
 
 strncpy(data.future_string1,"",MAX_FILENAME + 1);
 strncpy(data.future_string2,"",MAX_FILENAME + 1);
 data.future_int1 = 0;
 data.future_int2 = 0;
 
 set_discussion_names(conf->course_path, user->username, SELFTEST); /*shared_news_util.c */
 snprintf (data_path, MAX_PATH + 1, "%s%s", discussion_path, HOTPOT_FNAME);
 
 fp = fopen(data_path,"a");
 if(!fp)
  cs_critical_error(ERR_FOPEN_WRITE_FAILED,"");

 /* file locking not necessary here */ 
 if(fwrite(&data, sizeof(HOTPOTATO_INFO_STRUCT), 1, fp) != 1)
   cs_critical_error(ERR_FWRITE_FAILED,"");
 fclose(fp);
}






int
main ()
{
  char course[MAX_PATH + 1];	
  char key[MAX_KEY + 1];	
  char sender[MAX_USERNAME + 1];  
  char info_fname[MAX_FILENAME + 1];
  char score[MAX_HOTPOT_SCORE + 1];
  char start_time[MAX_HOTPOT_TIME + 1];
  char end_time[MAX_HOTPOT_TIME + 1];
  char exercise[MAX_HOTPOT_EXERCISE + 1];
  char orig_fname[MAX_FILENAME + 1];
  char system_fname[MAX_FILENAME + 1];
  int hidden;
  SESSION user;
  CONFIG_STRUCT conf;		/* the configuration read from config file */

  time_t elapsed_time;   /* number of seconds it took to answer quiz */
  time_t current_time;

  cs_cgi_init();
 // unsetenv ("CONTENT_TYPE");       /* Internet Explorer needs this! */  
  current_time = time (NULL);   
  read_parameters (course, key,sender,info_fname,
  			score,start_time,end_time,exercise,
  			orig_fname, system_fname, &hidden);
  read_configuration_file (course, &conf);	/* shared_util.c */
  validate_key (key, &user, &conf);	/* shared_util.c */

  if(!has_write_permission(&user, &conf))   /* shared_access.c */
      access_denied_error();

  
  elapsed_time = time_elapsed(start_time,end_time);
  
  save_data(sender,info_fname,score,start_time,
                 end_time,elapsed_time, exercise,orig_fname, system_fname, 
                 hidden, current_time, &conf, &user);

  cs_set_course_info(&conf);  
  show_results(score,exercise,elapsed_time,orig_fname, hidden,current_time);
  
  cs_cgi_display("hotpotato_record", 1);
  cs_cgi_destroy();

  return 0;			/* exit successfully */

}

