#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

#include "ClearSilver.h"
#include "sqlite3.h"
#include "global.h"
#include "custom.h"		/* for date FORMAT strings */
#include "grade.h"		/* for date FORMAT strings */
#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_grade_book_menu.h"
#include "manhat-lib/shared_file_util.h"
#include "manhat-lib/shared_grade_book_util.h"
#include "manhat-lib/shared_grade_book_db.h"

void
read_parameters ( char *course, char *key, int *item_id, char *username)
{
     char temp[MAX_KEY +1];

     cs_get_required_parameter("crs", course, MAX_PATH);
     cs_get_required_parameter("id", key, MAX_KEY);
     cs_get_required_parameter("item_id", temp, MAX_KEY);
     *item_id = atoi(temp);
     cs_get_required_parameter("username", username, MAX_USERNAME);


}





void  do_action(CONFIG_STRUCT *conf, int item_id, const char *course, const char *key, const char *username)
{

    get_one_item(conf, item_id, GRADE_BOOK_DB);
    if(!global_item_list || !global_item_list->head)
       cs_critical_error(ERR_GRADES_DB, "There is no item in db");
    set_item_list_values(1, 0); 

    get_user_score_logs(conf, item_id,  username, GRADE_BOOK_DB);  /* shared_grade_book_db.c */

    if(strcmp(global_item_list->head->is_letter_grade, "yes") ==0)
	 update_letter_log_list(conf,  item_id, GRADE_BOOK_DB, global_grade_list);
    set_score_log_values();    /* shared_grade_book_util.c */

    if(global_grade_list)
	 free_grade_list(global_grade_list);
       
    if(global_item_list)
	free_item_list(global_item_list);    /* shared_grade_book_util.c */

}




int
main ()
{
  char course[MAX_PATH +1];
  char key[MAX_KEY +1];
  char username[MAX_USERNAME +1];
  int item_id;
  SESSION user;
  CONFIG_STRUCT conf;
  
  cs_cgi_init();   /* shared_cs_util.h */
  read_parameters ( course, key, &item_id, username);
  read_configuration_file (course, &conf);	
  validate_key (key, &user, &conf);	


  if(user.group != FACULTY)
      cs_critical_error(ERR_REQUEST_DENIED, "grade_book");

  do_action(&conf, item_id, course, key, username);

  cs_load_lang("grade_book_enter_grades");
  cs_cgi_display ("grade_book_score_log", 1);
  cs_cgi_destroy();      

  return 0;			

}


