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

#include "global.h"
#include "custom.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_course_search.h"
#include "manhat-lib/shared_cs_course_search.h"
#include "manhat-lib/shared_server_string.h"
#include "manhat-lib/shared_cs_util.h"

static 
COURSE_SEARCH_NODE *read_parameters (char *key, COURSE_SEARCH_PARAMS *params, int *plaintext)
{
 SESSION user;
 COURSE_SEARCH_NODE *course_head;   /* shared_course_search.h */
 char tmp[51];
  
   cs_get_required_parameter ("id", key, MAX_KEY);   /* shared_cs_util.c */
   
   validate_super_key(key, &user);
   
   cs_read_course_search_params( user.username, params); /* shared_cs_course_search.c */

   course_head = build_course_search_list(params); /* shared_course_search.c */
   
   cs_get_optional_parameter("plain", tmp, 50);   /* shared_cgi_util.c */
   *plaintext = strlen(tmp);
   return course_head;
   
   
}  







void
set_courses( const char *key, COURSE_SEARCH_NODE *course_head, COURSE_SEARCH_PARAMS *params, int plaintext)
{
	
  COURSE_SEARCH_NODE *course_ptr;
  char server_string[MAX_PATH +1];
  char url[MAX_PATH +1];

  get_server_string(server_string, MAX_PATH +1);
  snprintf(url, MAX_PATH +1, "%s/%s/doorstep", server_string, ALIAS);
  cs_set_value("door_url", url);
              
  int normal_count = 0,
      standalone_count = 0,
      template_count = 0;
      

       
 for(course_ptr=course_head; course_ptr; course_ptr=course_ptr->next)
 {
  if(course_ptr->conf.template)
      template_count ++;
  else if(course_ptr->conf.standalone)
       standalone_count++;
  else
       normal_count++;   
  }
  cs_set_int_value("plain", plaintext);
  if(normal_count)
  {
     cs_set_int_value("normal_count", normal_count);
     set_matched_courses(course_head,   "ctr_group", 0, "super_config_course_list", key);
  }
  if(template_count)
  {
     cs_set_int_value("temp_count", template_count);
      set_matched_courses(course_head,   "temp_group", 2, "super_config_course_list", key);
  }
  if(standalone_count)
  {
     cs_set_int_value("stand_count", standalone_count);
      set_matched_courses(course_head,   "std_group", 1, "super_config_course_list", key);
  }    
     
}





int
main()
{
   char key[MAX_KEY + 1];
   COURSE_SEARCH_NODE *course_head;
   COURSE_SEARCH_PARAMS params;
   int plaintext;

   cs_cgi_init();    
   course_head = read_parameters(key, &params, &plaintext);
   set_courses( key, course_head, &params, plaintext);
   free_subdir_list(params.subdir_head);  /* shared_course_search.c */
   free_course_search_list(course_head);   /* shared_course_search.c */
   cs_cgi_display("super_print_course_list", 1);
   cs_cgi_destroy();
   return 0;

}
