#include <stdio.h>
#include <stdlib.h>
#include <string.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_cs_util.h"

void
write_xml(SURVEY_DATA *data, const char *xml_file)
{
   FILE *fp;
   fp = fopen(xml_file, "r+");
   if(!fp)
      cs_critical_error(ERR_FOPEN_WRITE_FAILED, "");
   if(fseek(fp, -strlen(SURVEY_END_TAG), SEEK_END))
      cs_critical_error(ERR_FSEEK_FAILED, "");
   write_text_custom(fp, data);
   xml_close(fp);
   fclose(fp);
}



void
do_action( SESSION *user, SURVEY_DATA *data, const char *count, int pre_id)
{
   char survey_path[MAX_PATH +1];
   char survey_file_path[MAX_PATH +1];
   
   get_survey_path(user, survey_path, count);
   snprintf(survey_file_path, MAX_PATH +1, "%s/%s", survey_path, SURVEY_XML_FNAME);
   data->id = get_valid_tag_id(survey_file_path); 
   if(pre_id == 0)
   {
       snprintf(survey_file_path, MAX_PATH +1, "%s/%s", survey_path, SURVEY_XML_FNAME);
       write_xml(data, survey_file_path); 
   }
   else
       insert_action( user,count, data, pre_id);
}

SURVEY_DATA *
read_parameters(int *is_admin, char *key, char *count, int *pre_id)
{
    int id = 0;   /* dummy id */
    read_com_parameters(is_admin, key, count, pre_id); /* shared_survey_read_param.c */
    return read_text_parameters(id);   /* shared_survey_read_param.c */
}
    
int 
main()
{
   int is_admin;
   char key[MAX_KEY +1];
   char count[MAX_PATH +1];
   SURVEY_DATA *data;
   SESSION user;
   int pre_id;

   cs_cgi_init();
   data = read_parameters(&is_admin, key, count, &pre_id);
   verify_key_path( &user, key, is_admin);

   do_action( &user, data, count, pre_id);
   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;
}
