#include "manhat-lib/shared_course_request_xml.h"
#include "manhat-lib/shared_file_util.h"
#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_wnec_roster_log.h"


char end_tag[15] = "</requests>\n";


void read_parameters(char *key, char *div)
{

     cs_get_required_parameter("id", key, MAX_KEY);
     cs_get_required_parameter("division", div, MAX_PATH);

}



REQUEST_COURSE *get_one_request(char *courseinfo, SESSION *user)
{
    REQUEST_COURSE *ptr;
    char *se_char1, *se_char2;
    char course[strlen(courseinfo) +1];
    
    ptr = (REQUEST_COURSE *)malloc(sizeof(REQUEST_COURSE));
    if(!ptr)
       cs_critical_error(ERR_MALLOC_FAILED, "get_one_request()");

    strncpy(ptr->realname, user->realname, MAX_NAME +1);     
    strncpy(ptr->username, user->username, MAX_USERNAME +1);    
    
    strcpy(course,courseinfo);  
    se_char1 = strchr(course, ':');
    if(se_char1)
    {
        *se_char1 = '\0';
        strncpy(ptr->sis_id, course, MAX_COURSE_ID +1);     
        strncpy(ptr->new_id, course, MAX_COURSE_ID +1);     
	se_char1++;
    }
    else
      cs_critical_error(ERR_PARAM_FORMAT, "admin_add_courses()");
    se_char2 = strchr(se_char1, ':');
    if(se_char2)
    {
           *se_char2 = '\0';
            strncpy(ptr->subdir, se_char1, MAX_COURSE_SUBDIR +1);     
	    se_char2++;  
    }
   else
	   cs_critical_error(ERR_PARAM_FORMAT, "admin_add_courses()");
   se_char1 = strchr(se_char2, ':');
   if(se_char1)
   {
	  *se_char1 = '\0';
          strncpy(ptr->course_title, se_char2, MAX_COURSE_TITLE +1);     
	  se_char1++;
           
   }
   else
       cs_critical_error(ERR_PARAM_FORMAT, "admin_add_courses()");
        
   se_char2 = strchr(se_char1, ':');
   if(se_char2)
   {
	 *se_char2 = '\0';
         strncpy(ptr->course_code, se_char1, MAX_COURSE_NO +1);     
         se_char2++;
   }
   else
       cs_critical_error(ERR_PARAM_FORMAT, "admin_add_courses()");
   strncpy(ptr->course_semester, se_char2, MAX_SEMESTER +1);     
   ptr->next = 0; 
   return ptr;
}




REQUEST_COURSE *get_request_list(SESSION *user)
{
   REQUEST_COURSE *head = 0, *current = 0, *ptr;
   HDF *obj;
   char *str;

   str = hdf_get_value(global_cgi->hdf, "Query.course_list.0",  0);
   if(str)
   {
        obj = hdf_get_child(global_cgi->hdf, "Query.course_list");
        while(obj)
        {
            str = obj->value;
            if(str)
            {
                ptr = get_one_request(str, user);
                if(!head)
                  head = ptr;
                else
                  current->next = ptr;
                current = ptr;
            }

           obj = obj->next;
       }

   }
   else
    {
       str = hdf_get_value(global_cgi->hdf, "Query.course_list",  0);
       if(!str)
            cs_critical_error(ERR_PARAM_MISSING, "get_request_list()");
        head = get_one_request(str,user);
    }
    return head;
}



void write_one_request(REQUEST_COURSE *one, FILE *fp, const char *time_string)
{
     char str[MAX_PATH +1];

     fprintf(fp, "<request>\n");
     fprintf(fp, " <faculty_realname>%s</faculty_realname>\n", one->realname);
     fprintf(fp, " <faculty_username>%s</faculty_username>\n", one->username);
     fprintf(fp, " <sis_id>%s</sis_id>\n", one->sis_id);
     fprintf(fp, " <subdir>%s</subdir>\n", one->subdir);
     fprintf(fp, " <new_id>%s</new_id>\n", one->new_id);
     fprintf(fp, " <course_code>%s</course_code>\n", one->course_code);
     fprintf(fp, " <course_title>%s</course_title>\n", one->course_title);
     fprintf(fp, " <course_term>%s</course_term>\n", one->course_semester);
     fprintf(fp, " <time>%s</time>\n", time_string);
     fprintf(fp, "</request>\n");
	 snprintf(str, MAX_PATH +1, "%s %s", one->username, one->realname);
	 update_roster_log(ROSTER_REQUEST_COURSE, "", one->course_code, one->course_title, -1, -1, str); /* shared_wnec_roster_log.h */ 
      
}


void write_data(REQUEST_COURSE *head, const char *file)
{
     FILE *fp;
     REQUEST_COURSE *ptr;
     char time_string[MAX_TIMESTRING +1];
     time_t now;

     now = time (NULL);
     strftime (time_string, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT,
		                               localtime (&now));



     fp = fopen(file, "w");
     if(!fp)
	  cs_critical_error(ERR_FOPEN_WRITE_FAILED, file);
     get_exclusive_lock(fileno(fp),1);
     fprintf(fp, "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\n");
     fprintf(fp, "<!-- Manhattan course data -->\n");
     fprintf(fp, "<requests>\n");

     for(ptr = head; ptr; ptr = ptr->next)
       write_one_request(ptr, fp, time_string);
       
     fprintf(fp, end_tag);
     release_lock(fileno(fp));
     fclose(fp);
}

int find_this_request(REQUEST_COURSE *this_course, REQUEST_COURSE_LIST *list)
{
      for(list->current = list->head; list->current; list->current = list->current->next)
      {
	  if( !strcmp(list->current->sis_id, this_course->sis_id) &&
	      !strcmp(list->current->subdir, this_course->subdir))
	      return 1;
      }
      return 0;
}


void  append_data(REQUEST_COURSE *head,  char *file)
{
     FILE *fp;
     REQUEST_COURSE *ptr;
     char time_string[MAX_TIMESTRING +1];
     time_t now;
     REQUEST_COURSE_LIST *list;
    
     list = xml_request_course_parser(file);

     now = time (NULL);
     strftime (time_string, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT,
		                               localtime (&now));
     fp = fopen(file, "r+");
     if(!fp)
	  cs_critical_error(ERR_FOPEN_WRITE_FAILED, file);
     get_exclusive_lock(fileno(fp),1);
     if(fseek(fp, -strlen(end_tag), SEEK_END))
       cs_critical_error( ERR_FSEEK_FAILED, file);
     
     for(ptr = head; ptr; ptr = ptr->next)
     {
       if(!find_this_request(ptr, list))
       {
          write_one_request(ptr, fp, time_string);
       }
     }
     fprintf(fp, end_tag);
     release_lock(fileno(fp));
     fclose(fp);
     free_request_list(list);
}


void
save_requests(REQUEST_COURSE *head,  char *div)
{
    char file[MAX_PATH +1];

    snprintf(file, MAX_PATH +1, "../auto_update/request");
    mkdir(file, 0777);
    get_request_list_filename(div, file);  /* shared_course_request_xml.h */
    
    update_roster_log(ROSTER_REQUEST_COURSE, file, "", "", -1, -1, "Start request"); 
    if(file_exists(file))
        append_data(head, file);
    else
        write_data(head, file);
    update_roster_log(ROSTER_REQUEST_COURSE, file, "", "", -1, -1, "End request"); 
        
}


void  set_data(REQUEST_COURSE *head)
{
      REQUEST_COURSE *ptr;
      char name[MAX_PATH];
      int i = 0;
      for(ptr = head; ptr; ptr = ptr->next)
      {
         snprintf(name, MAX_PATH, "course.%d.course_title", i);
	 cs_set_value(name, ptr->course_title);
         snprintf(name, MAX_PATH, "course.%d.course_code", i);
	 cs_set_value(name, ptr->course_code);
         snprintf(name, MAX_PATH, "course.%d.course_semester", i);
	 cs_set_value(name, ptr->course_semester);
	 i++;
      }

}


void do_action(SESSION *user,  char *div)
{
    REQUEST_COURSE *head;

    head = get_request_list(user);
    save_requests(head, div);
    set_data(head);
    free_request_head(head);

}


int main()
{
   char key[MAX_KEY +1];
   SESSION user;
   char division[MAX_PATH +1];

   cs_cgi_init(); 
   read_parameters(key, division);
   validate_server_key(key, &user);
   cs_set_value("instructor", user.realname);
   do_action(&user, division);
   cs_cgi_display("admin_add_courses", 1);
   cs_cgi_destroy(); 
   return 0;
}
    



	       
