#include <stdio.h>
#include <stdlib.h>

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

#include "manhat-lib/shared_record_parser.h"
#include "manhat-lib/shared_super_key.h"
#include "manhat-lib/shared_survey_xml_parser.h"
#include "manhat-lib/shared_server_string.h"
#include "manhat-lib/shared_survey_bar_graph.h"
//#include "manhat-lib/shared_strtrm.h"
#include "manhat-lib/shared_survey_www_util.h"
#include "manhat-lib/shared_cs_util.h"


void
read_parameters( char *count, char *key, int *crs, int *password)
{

    char is_edit[20];

    cs_get_required_parameter("id", count, MAX_PATH);
    cs_get_optional_parameter("key", key, MAX_KEY);
    cs_get_optional_parameter("crs", is_edit, 19);
    if(strlen(is_edit))
       *crs = atoi(is_edit);
    else
       *crs = -1;

    cs_get_optional_parameter ("pass", is_edit, 19);
    if(strlen(is_edit))
       *password = atoi(is_edit);
    else
       *password =0;

}

   
   
void
do_action( const char *count)
{
    char fname[MAX_PATH +1];
    char file_path[MAX_PATH +1];
    char record_fname[MAX_PATH +1];

    snprintf(file_path, MAX_PATH +1, "../%s/%s/%s", 
		          SURVEY_DIR, SURVEY_WWW_DIR, count); 

    snprintf(fname, MAX_PATH+1, "%s/%s", file_path, SURVEY_XML_FNAME);
    snprintf(record_fname, MAX_PATH+1, "%s/%s", file_path, SURVEY_RESULT_FNAME);

    
    
    /* -1 means to use the number of recipients recorded
    ** in the xml file
    */
    if(!set_survey_graph_results(fname,record_fname,-2))  /* shared_survey_bar_graph.c */
           cs_critical_error(ERR_SURVEY_RESULT_NOT_AVAILABLE, "");
     cs_set_value("survey.type", "www_accessible");

}

int
main()
{
    char count[MAX_PATH +1];
    char key[MAX_KEY +1];
    int crs, password, realpass;
    SESSION user;

    cs_cgi_init();
    read_parameters( count, key, &crs, &password);
    realpass = read_password(count);  /* shared_survey_www_util.h */
    if(password == 0 && strlen(key) && crs ==1)
    {
       validate_super_key(key, &user);
       do_action( count);
       cs_cgi_display("survey_bar_graph", 1);
    }
    else if(password == 0 && !strlen(key) && crs ==-1)    /* protected result print access code form */
    {
      cs_set_int_value("display", 1);
      cs_cgi_display("survey_www_access_form", 1); 
    }
    else if(password == realpass)
    {
       do_action( count);
       cs_cgi_display("survey_bar_graph", 1);
    }
    else
    {
      cs_set_int_value("display", 1);
      cs_cgi_display("survey_www_access_form", 1); 
    }
    cs_cgi_destroy();

    return 0;
}

       
    
	
