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

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_survey_util.h"
#include "manhat-lib/shared_super_key.h"
#include "manhat-lib/shared_survey_xml_parser.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_survey_modify.h"
#include "manhat-lib/shared_cs_util.h"


void
set_data(  SURVEY_DATA *data)
{
   char *str = 0;

    cs_set_int_value("modify", 1);
    cs_set_int_value("data.id", data->id);
    str = replace_disallowed_html_code(data->caption);
    cs_set_value("data.caption", str);
    free(str);
    cs_set_value("data.left_cols", data->left_cols);
    cs_set_value("data.steps_bgcolor", data->steps_bgcolor);
}





void
do_action(int is_admin, const char *key, const char *count, int pre_id,  SESSION *user)
{
     SURVEY_LIST *list;
     char file_path[MAX_PATH +1];
     char survey_path[MAX_PATH +1];
     SURVEY_DATA *data;
     char *str;

     str = hdf_get_value(global_cgi->hdf, "Query.modify", 0);
     if(str)
     {
	get_survey_path(user, survey_path, count); /* shared_survey_path_util.c */
	snprintf(file_path, MAX_PATH +1, "%s/%s",survey_path, SURVEY_XML_FNAME);
	list= survey_data_parser(file_path);
	data = get_one_survey_data(list, pre_id);
	
	if(data)
	{
           set_data(data);
           insert_survey_spell_check_button();   /* shared_survey_util.c */
	   cs_cgi_display("survey_new_form", 1);
	}
	else
	   cs_critical_error(ERR_SURVEY_NO_DATA, "");
	free_survey_data(data);
	free_survey_data_list(list);
     }
     else 
     {
         str = hdf_get_value(global_cgi->hdf, "Query.paste", 0);
        if(str)
	{
           paste_action( user, is_admin, key,  count,   pre_id); /* shared_survey_modify.c*/
           printf("Location: %s?admin=%d&id=%s&count=%s#%d\n\n",
	                       "survey_new", is_admin, key, count, pre_id);
	}
	else
         printf("Location: %s?admin=%d&id=%s&count=%s&pre_id=%d\n\n",
	     "survey_custom_form", is_admin, key, count, pre_id);
     }
}

	   

int
main()
{
   int  is_admin;
   char key[MAX_KEY +1];
   char count[MAX_PATH +1];
   int pre_id;
   SESSION user;
    
   cs_cgi_init();
   read_com_parameters(&is_admin, key,  count, &pre_id);  /* shared_survey_read_param.c */

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

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

   cs_cgi_destroy();
   return 0;
}

