#include <stdio.h>
#include <stdlib.h>
#include "global.h"
#include "survey.h"

#include "manhat-lib/shared_survey_util.h"
#include "manhat-lib/shared_survey_modify.h"
#include "manhat-lib/shared_survey_read_param.h"
#include "manhat-lib/shared_survey_path_util.h"
#include "manhat-lib/shared_survey_page.h"
#include "manhat-lib/shared_cs_util.h"

SURVEY_DATA *
read_parameters(int *is_admin, char *key, char *count)
{
   int id;

   read_com_parameters(is_admin, key, count, &id);  /* shared_survey_read_param.c */
   return read_choice_parameters(id);     /* shared_survey_read_param.c */
   
}



void
set_choices(SURVEY_DATA *data)
{
  #define MAX_TMP_NAME 40
   int i =0;
   char name[MAX_TMP_NAME +1];
   ELE_CHOICE *ptr;
   char *str;

   for(ptr = data->head; ptr; ptr = ptr->next)
   {
       snprintf(name, MAX_TMP_NAME +1, "data.choice.%d", i);
       str = replace_disallowed_html_code(ptr->choice);
       cs_set_value(name, str);
       free(str);
        i++;
   }
    cs_set_int_value("number_choices", i);
 #undef MAX_TMP_NAME
}





void
set_data_value(SURVEY_DATA *data)
{
    char *str;

    cs_set_int_value("data.id", data->id);
    str = replace_disallowed_html_code(data->caption);
    cs_set_value("data.caption", str);
    cs_set_value("data.multi", data->steps_bgcolor);
    free(str);
    set_choices(data);

}




int 
main()
{
   int  is_admin;
   char key[MAX_KEY +1];
   char count[MAX_PATH +1];
   SURVEY_DATA *data;
   SESSION user;
   char *str =0;
   int number =0;

   cs_cgi_init();   /* shared_cs_util.c */
   data = read_parameters(&is_admin, key, count); 
   verify_key_path(&user, key, is_admin);   /* shared_survey_path_util.c */

   str = hdf_get_value(global_cgi->hdf, "Query.more", 0);
   if(str)
   {
      number = hdf_get_int_value(global_cgi->hdf, "Query.number_choices",0);
      set_data_value(data);
      cs_set_int_value("number_choices", number +4);
      cs_set_int_value("modify", 1);
      cs_load_lang("shared_survey_form");
      cs_cgi_display("survey_choice_form", 1);
   }
   else
   {
      modify_action( &user, count, data);  /* shared_survey_modify.c */
      printf("Location: %s?admin=%d&id=%s&count=%s&target=%d#%d\n\n", 
		   "survey_new", is_admin, key, count, data->id, data->id);
   }
   free_survey_data(data);
   cs_cgi_destroy();   /* shared_cs_util.c */

   return 0;
}
