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

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

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_super_key.h"
#include "manhat-lib/shared_survey_path_util.h"
#include "manhat-lib/shared_survey_table.h"
#include "manhat-lib/shared_survey_xml_parser.h"





void
read_parameters(int *is_admin, char *key, char *count, int *csv)
{

    char tmp[10];

    cs_get_required_parameter("id", key, MAX_KEY);
    cs_get_required_parameter("count", count, MAX_PATH);

    cs_get_optional_parameter("admin", tmp, 9);
    *is_admin = !*tmp? 0: atoi(tmp)? 1 : 0;
    
    cs_get_optional_parameter("csv", tmp, 9);
    *csv = !strcmp(tmp, "yes") ? 1 : 0;

}

     
   



void
do_action(int is_admin, char *key, SESSION *user, const char *count, int csv)
{
    char fname[MAX_PATH +1];
    char survey_path[MAX_PATH +1];
    RECORD_LIST *list;    /* shared_survey_record_html_parser.h */
    struct stat buf;
    int total = 0;
    char url[MAX_PATH +1];
    SURVEY_LIST *survey_list;    /* survey.h */

    get_survey_path(user, survey_path, count);     /* shared_survey_path_util.c */
    snprintf(fname, MAX_PATH +1, "%s/%s",survey_path, SURVEY_RESULT_FNAME);
    
    if(stat(fname, &buf))
       cs_critical_error(ERR_SURVEY_RESULT_NOT_AVAILABLE, "");
    
    list = (RECORD_LIST *)record_html_parser(fname); /* shared_survey_record_html_parser.c */

    if(list->head)
    {
      if(csv)
      {
           snprintf(fname, MAX_PATH +1, "%s/%s",survey_path, SURVEY_XML_FNAME);
           survey_list = survey_data_parser(fname); 
           send_survey_results_csv(list, -1, "mymanhattan", survey_list);   /* shared_survey_table.c */
	   free_survey_data_list(survey_list);

      }
      else
      {

       list->current = list->head;
       set_survey_table_heading(list->current, -1);
       while(list->current)
        {
          set_survey_table_one_record(list->current, -1, total); /*shared_survey_table.c */
          list->current = list->current->next;
	  total++;
	
        }
       set_survey_table_basic_data(list,  total, -1);    /* shared_survey_table.c */
       snprintf(url, MAX_PATH +1, "%s?admin=%d&amp;id=%s&amp;count=%s&amp;csv=yes", 
		       "survey_mymanhattan_table", is_admin, key, count);
       cs_set_value("csv_url", url);
       cs_set_value("survey_type", "mymanhattan");
      }
    }
    else
      cs_critical_error(ERR_SURVEY_RESULT_NOT_AVAILABLE, "");



    free_record_html_list(list);

}




int
main()
{
    char count[MAX_PATH +1];
    char key[MAX_KEY+1];
    int is_admin, csv;
    SESSION user;

    cs_cgi_init();
    read_parameters (&is_admin, key, count, &csv);

    verify_key_path(&user, key, is_admin);   /* shared_survey_path_util.h */

    do_action(is_admin, key, &user,  count, csv);

    if(!csv)
        cs_cgi_display("survey_table_data", 1);


     cs_cgi_destroy();


    return 0;
}

       
    
	
