#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

#include "global.h"
#include "manhat-lib/shared_calendar_util.h"
#include "manhat-lib/shared_cs_util.h"

void
read_parameters(char *textfield_name)
{
    cs_get_required_parameter("textId", textfield_name, MAX_KEY);
}

void
set_nav(int year, int month, int selected_day , const char *id)
{
     int pre_year, pre_month, next_year, next_month;
     char url[MAX_PATH +1];

     get_pre_next(year, month, &pre_year, &pre_month, &next_year, &next_month);


     snprintf(url, MAX_PATH +1, "%s?year=%d&amp;month=%d&amp;today=%d&amp;textId=%s", 
		     "calendar_pick",  pre_year, pre_month, 1, id);
     cs_set_value( "preurl", url);

     snprintf(url, MAX_PATH +1, "%s?year=%d&amp;month=%d&amp;today=%d&amp;textId=%s", 
		     "calendar_pick",  next_year, next_month, 1, id);
     cs_set_value( "nexturl", url);

     cs_set_int_value( "month_name", month);
     cs_set_int_value( "year", year);
     
}

void
set_body_calendar(int year, int month, int selected_day,   int today, const char *id) 
{
      int i, start, month_days;
      char url[MAX_PATH +1];
      char name[MAX_PATH +1];

      start = get_this_month_start_day( year,  month );
      month_days = get_month_days(month, year);

      cs_set_int_value("month_days", month_days);
      cs_set_int_value("year", year);
      cs_set_int_value("start", start);
      cs_set_int_value("today", today);
      
      for(i = 1; i<=month_days; i++)
      { 
         snprintf(url, MAX_PATH +1, "self.opener.document.getElementById('%s').value='%s%d/%s%d/%d'; window.close()", 
	      id, month < 10 ? "0":"", month, i < 10 ? "0":"", i, year); 
         snprintf(name, MAX_PATH +1, "day.%d.url", i);
         cs_set_value( name, url);
     }
     
}

void
set_calendar(const char *id)
{
    time_t current;
    struct tm *today;
    int year =0, month =0, selected_day =0;

    current = time(NULL);
    today = localtime(&current);
   
    year = hdf_get_int_value (global_cgi->hdf, "Query.year", 0);
    month = hdf_get_int_value (global_cgi->hdf, "Query.month", 0);
    selected_day = hdf_get_int_value (global_cgi->hdf, "Query.today", 0);
    
    if(!year && !month)
    {
       year = today->tm_year +1900;
       month = today->tm_mon + 1;
       selected_day = today->tm_mday;
    }

    set_nav(year, month, selected_day, id);
    if(year == today->tm_year + 1900 && month == today->tm_mon +1)
       set_body_calendar(year, month, selected_day,   today->tm_mday, id); 
    else
       set_body_calendar(year, month, selected_day,   0, id); 
}


int
main ()
{
  char textfield_id[MAX_KEY +1];
  cs_cgi_init();
  read_parameters(textfield_id);

  set_calendar(textfield_id);

  cs_cgi_display ("calendar_pick", 1);
  cs_cgi_destroy();              

  return 0;			/* exit successfully */

}

