#include <stdio.h>
#include <string.h>

#include "global.h"
#include "custom.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"


static void
read_parameters (char *course, char *key)
{

  cs_get_required_parameter ("crs", course, MAX_PATH);
  cs_get_required_parameter ("id", key, MAX_KEY);
}



void
get_chat_username (char *chat_username, SESSION *user)
{
  char *ptr;

  strncpy (chat_username, user->realname, MAX_NAME);
  for (ptr = chat_username; *ptr; ptr++)
    if (*ptr == ' ')
      *ptr = '-';
}





static void
set_chat_applet_data (const char *course, const char *key, SESSION *user)
{

  char chat_username[MAX_NAME];
  char url[MAX_PATH];


  cs_set_int_value("server_port", MELANGE_PORT);
  
  get_chat_username (chat_username, user);
  snprintf(url, MAX_PATH, "%s:%s", chat_username, course);
  cs_set_value("chat_username", url);

  snprintf (url, MAX_PATH , "%s?crs=%s&id=%s","chat_close", course, key);
  cs_set_value("return_url", url);

}




/* simply writes current time to chat_access.log file in the users directory */
static void
log_this_access (char *username, CONFIG_STRUCT *conf)
{
  FILE *fp;
  char logpath[MAX_PATH + 1];
  time_t now;

  now = time (NULL);

  snprintf (logpath, MAX_PATH + 1, "%s%s/%s/%s", 
   			conf->course_path,PEOPLE_DIR,
	    			username, CHAT_ACCESS_LOG);
  fp = fopen (logpath, "a+");
  fwrite (&now, sizeof (time_t), 1, fp);
  fclose (fp);
}






int
main ()
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  SESSION user;
  CONFIG_STRUCT conf;

  cs_cgi_init();

  read_parameters (course, key);
  read_configuration_file (course, &conf);	/* shared_util.c */
  validate_key (key, &user,  &conf);	/* shared_util.c */

  log_this_access (user.username, &conf);

  set_chat_applet_data (course, key, &user);

  /** LOOK - uses a cs template called "super_chat_enter" ***/
  cs_cgi_display("super_chat_enter", 1);
  cs_cgi_destroy();
  return 0;			/* exit successfully */

}

