#include <stdio.h>
#include <string.h>

#include "../global.h"
#include "../survey.h"

#include "shared_lock.h"
#include "shared_cs_util.h"



void 
read_survey_release_data(CONFIG_STRUCT *conf, const char *sender, const char *info_fname,  SESSION *user,
                                           int *already_taken, char *survey_dir, SURVEY_RELEASE_RECORD *release,
                                           NEWS_INFO *infofile_info)
{

 FILE *fp;
 int fd;
 char release_record_path[MAX_PATH + 1];
 int found;
 char infopath[MAX_PATH + 1];
 ATTACHMENT attachment;
 NEWS_PERSON person;
 
  /*** read the info file */
  snprintf (infopath, MAX_PATH + 1, "%speople/%s/%s/%s", conf->course_path,
	    sender,
	    SURVEYS_DIR, info_fname);

  fp = fopen (infopath, "r");
  if (!fp)
    cs_critical_error (ERR_FOPEN_READ_FAILED, "");
  
  fd = fileno(fp);
  get_shared_lock(fd,1);         /* shared_lock.c */
    
  if (fread (infofile_info, sizeof (NEWS_INFO), 1, fp) != 1)
    cs_critical_error (ERR_FREAD_FAILED, "");

  /*we know there's exactly one attachment */
  if (fread (&attachment, sizeof(ATTACHMENT), 1, fp) != 1)
    cs_critical_error (ERR_FREAD_FAILED, "");
  strncpy(survey_dir, attachment.unique_fname, MAX_FILENAME + 1);     
   
  /** now see if this user read the message */
  found = 0;
  while (!found && (fread(&person, sizeof(NEWS_PERSON), 1, fp) == 1))
    {
     found = !strcmp(person.username, user->username) &&   person.time_read;
    }
    
  *already_taken = found;
  release_lock(fd);   /* shared_lock.c */
  fclose(fp);
  
     
  
  /** now read the release data file, which includes info on 
  *** when the results of this survey will be made available
  *** to the teachers
  **/ 
  snprintf (release_record_path, MAX_PATH + 1, "%s%s/%s/%s/%s/%s", 
            conf->course_path,
            PEOPLE_DIR,
	    sender,
	    SURVEYS_DIR,
	    survey_dir,
	    SURVEY_RELEASE_FNAME
	    );

   fp = fopen(release_record_path, "r");
   if(!fp)
       cs_critical_error(ERR_CANT_OPEN_RELEASE_DATAFILE, release_record_path);
   fd = fileno(fp);
   get_shared_lock(fd,1);
   if(fread(release, sizeof(SURVEY_RELEASE_RECORD), 1, fp) != 1)
       {
        release_lock(fd);
        cs_critical_error(ERR_ERROR_READING_RELEASE_DATAFILE, release_record_path);
       }
   release_lock(fd);
   fclose(fp);
 
}      



int is_unanswered_required_survey(CONFIG_STRUCT *conf, const char *sender, const char *info_fname, SESSION *user)
{

 int already_taken;
 char survey_dir[MAX_FILENAME + 1];
 SURVEY_RELEASE_RECORD release;
 NEWS_INFO infofile_info;

if(user->group == FACULTY) 
    return 0;
    
read_survey_release_data(conf, sender, info_fname, user,
                         &already_taken, survey_dir, &release,
                                           &infofile_info);
                                           
return !already_taken && release.student_answer_required;


}


