#include "shared_grade_book_view.h"

static void
get_redfile_path (char *redfile_path, const char *username, 
				CONFIG_STRUCT *conf, const char *reader_username)
{
  static int n = 0;
  char filedir[MAX_PATH + 1];
  char unique_fname[MAX_FILENAME + 1];
  
  
  snprintf (filedir, MAX_PATH + 1, "%s%s/%s/%s/", conf->course_path, PEOPLE_DIR,  username, GRADES_DIR);

  
  do
    {
      n++;
      snprintf(unique_fname, MAX_FILENAME + 1, "%d%s%d.red", n, reader_username, getpid());
      snprintf (redfile_path, MAX_PATH + 1, "%s%s", filedir, unique_fname);
    }
  while (file_exists(redfile_path));  /* shared_file_util.c */

}






static void
write_red_file (char *pathname, SESSION *user)
{
  GRADES_INFO_STRUCT info;
  FILE *fp;

  strncpy (info.username, user->username, MAX_USERNAME + 1);
  strncpy (info.realname, user->realname, MAX_NAME + 1);
  info.time_read = time (NULL);

  fp = fopen (pathname, "w");
  if (!fp)
    cs_critical_error (ERR_RED_OPEN, "");

  fwrite (&info, sizeof (GRADES_INFO_STRUCT), 1, fp);

  fclose (fp);
}




static void
deliver_red_files (CONFIG_STRUCT *conf, SESSION *user)
{
  P_NODE *ptr, *pers_head;			/* shared_person_list.c */
  char red_path[MAX_PATH + 1];

  
  pers_head = build_option_person_list (conf);	/* shared_person_list.c */
  for (ptr = pers_head; ptr; ptr = ptr->next)
    if (ptr->data.group == FACULTY)
     {
       get_redfile_path (red_path, ptr->data.username, conf, user->username);
       write_red_file (red_path, user);
     }
   free_option_person_list (pers_head);	/* shared_person_list.c */  
   
}


void
handle_new_file (CONFIG_STRUCT *conf, SESSION *user)
{

  char fname[MAX_PATH + 1];
  struct stat buf;


  snprintf (fname, MAX_PATH + 1, "%speople/%s/grades/%s", conf->course_path,
	    user->username, GRADES_NEW_FNAME);
  if (!stat (fname, &buf))	/* if file exists */
    {
      unlink (fname);
      if (user->group != FACULTY)
	deliver_red_files (conf, user);
    }
}

void
handle_red_new_file(CONFIG_STRUCT *conf, SESSION *user)
{
   deliver_red_files (conf, user);
   handle_new_file (conf, user);
    
}
	

