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

#include "global.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_news_util.h"
#include "manhat-lib/shared_clipboard_util.h"
#include "manhat-lib/shared_translate_url.h" 
#include "manhat-lib/shared_access.h" 
#include "manhat-lib/shared_spelling_util.h"


static void
read_parameters (char *course, char *key, char *from_prog, int *paste)
{
  char tmp[20];

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

  cs_get_optional_parameter ("paste", tmp, 19);
  if (strlen(tmp) ==0 )	/* we are not pasting from clipboard */
    *paste = 0;			/* not pasting */
  else
    *paste = 1;			/* we are pasting from clipboard */

}





static void
new_memo_header (char *course, char *key, char *from, CONFIG_STRUCT *conf, SESSION *user)
{
  char temp[MAX_PATH + 1];
  int empty_clipboard;
 /** clipboard_empty() is in shared_clipboard_utils.c */
  empty_clipboard = (user->group != FACULTY) ||
    clipboard_empty (user->username, conf->course_path, user);

  cs_set_course_info(conf);
  cs_set_current_time();
  insert_spell_check_button(conf);   /* shared_spelling_util.c */

  /* EMOTICONS_DISABLED is #defined in global.h */
  cs_set_int_value("emoticons_disabled" , EMOTICONS_DISABLED(conf->misc) ? 1 : 0);
  
  cs_set_int_value("msg.textarea.cols", editor_width_config(conf->misc));  /* shared_news_util.c */
  cs_set_int_value("msg.textarea.wrap", USE_TEXTAREA_HARD_WRAP);
  
 cs_set_int_value("msg.subject.max", MAX_SUBJECT -1);
 
  /* translate special chars */
  translate_url_substitutes (temp, from, MAX_PATH + 1,1);	/* shared_translate_url.c */

  if (!empty_clipboard)
      cs_set_int_value("paste", 1);
   cs_set_value("back_url", temp); 
   cs_set_value("crs", course);
   cs_set_value("id", key);
   cs_set_value("from", from);
}




static int
get_clipboard_info (CLIPBOARD_INFO * clipboard_info, char *clipboard_path,
                    SESSION *user)
{
  char fullpath[MAX_PATH + 1];
  FILE *fp;

  snprintf (clipboard_path, MAX_PATH + 1, "%s%s/", CLIPBOARD_PATH, user->id);
  snprintf (fullpath, MAX_PATH + 1, "%s%s", clipboard_path,
	    CLIPBOARD_INF_FNAME);
  fp = fopen (fullpath, "r");
  if (!fp)
    return 1;
  if (fread (clipboard_info, sizeof (CLIPBOARD_INFO), 1, fp) != 1)
    {
      fclose (fp);
      return 1;
    }

  fclose (fp);
  return 0;
}


/*** prints the first line of the clipboard's msg file */
static void
print_url (const char *clipboard_path, const char *msg_fname)
{
  FILE *fp;
  char fullpath[MAX_PATH + 1];
  char *buffer, ch;
  int i, big_buffer = 200;

  buffer = (char *) malloc(sizeof(char)*big_buffer +1);
  if(!buffer)
	cs_critical_error(ERR_MALLOC_FAILED, "");

  snprintf (fullpath, MAX_PATH + 1, "%s%s", clipboard_path, msg_fname);
  fp = fopen (fullpath, "r");
  if (!fp)
    cs_critical_error (ERR_FOPEN_READ_FAILED, "");
  
  *buffer = '\0';
  i =0;
  while( (ch = getc(fp)) != '\n')
  {
      if((int)strlen(buffer) >= big_buffer)
      {
	 buffer = realloc(buffer, big_buffer *2 +1);
	 big_buffer = big_buffer *2;
      }
      buffer[i] = ch;
      buffer[i +1] = '\0';
      i++;
  }
  fclose (fp);
  cs_set_value("msg.url.value", buffer);
  free(buffer);
}





static void
paste_textarea (const char *clipboard_path,
		   const char *msg_fname,
		   const char *sender_username,
		   char *sender_realname, int grp, SESSION *user, CONFIG_STRUCT *conf)
{
  FILE *fp;
  char fullpath[MAX_PATH + 1];
  char ch, url;
  int longest;
  int count = 0;
  char *buffer;
  int big_buffer = 200;
  int i;

  longest = editor_width_config(conf->misc);   /* shared_news_util.c */
  snprintf (fullpath, MAX_PATH + 1, "%s%s", clipboard_path, msg_fname);
  fp = fopen (fullpath, "r");
  if (!fp)
    cs_critical_error (ERR_FOPEN_READ_FAILED, "");

  /* read characters from the file until we've read a newline
  ** this skips past the first line of the file, which is the URL
  */
  ch = 0;
  while ( (fread (&ch, 1, 1, fp) == 1) && (ch != 10) )
   {
   
   }
   
   
  
  while (fread (&ch, 1, 1, fp) == 1)
    if (ch == 10)
      {
	if (count > longest)
	  longest = count;
	count = 0;
      }
    else
      count++;
  cs_set_int_value("msg.textarea.cols", longest);

  if (fseek (fp, 0L, SEEK_SET))
    cs_critical_error (ERR_FSEEK_FAILED, "");

  if (strcmp (user->username, sender_username))
      cs_set_value("feedback", sender_realname);
  if (grp == INTERNET_RESOURCES)
  {
    while((url=getc(fp)) != '\n')
    {
    }	/* swallow first line - it's the URL */
  }
  buffer = (char*) malloc(sizeof(char) * big_buffer +1);
  if(!buffer)
    cs_critical_error (ERR_MALLOC_FAILED, "");
  
  *buffer = '\0';
  i =0;
  while (fread (&ch, 1, 1, fp) == 1)
  {
      if((int)strlen(buffer) >= big_buffer)
      {
	 buffer = realloc(buffer, big_buffer *2 +1);
	 big_buffer = big_buffer *2;
      }
      buffer[i] = ch;
      buffer[i +1] = '\0';
      i++;
  }
  fclose (fp);
  cs_set_value("msg.textarea.body", buffer);
  free(buffer);
}





static int
do_paste (SESSION *user, CONFIG_STRUCT *conf)
{
  CLIPBOARD_INFO clipboard_info;
  char clipboard_path[MAX_PATH + 1];
  char *ptr;


  if (user->group != FACULTY)
    cs_critical_error (ERR_REQUEST_DENIED, "");

  if (get_clipboard_info (&clipboard_info, clipboard_path, user))
    return 1;			/* clipboard is empty */



  /* print clipboard subject but must replace quotes " with &quot; */
   ptr = replace_quot( clipboard_info.subject);

   cs_set_value("msg.subject.value", ptr);
   free(ptr);

  /* handle URL */

  if (clipboard_info.group == INTERNET_RESOURCES)
    print_url (clipboard_path, clipboard_info.msg_fname);
   
  /* handle textarea */
  paste_textarea (clipboard_path, clipboard_info.msg_fname,
		     clipboard_info.sender_username,
		     clipboard_info.sender_realname, clipboard_info.group, user, conf);


  if (clipboard_info.attachments)
     cs_set_int_value("attachments", 1);

  return 0;			/* paste successful */

}


static void
display_new_memo_form (char *course, char *key, char *from_prog, int paste,
                       CONFIG_STRUCT *conf, SESSION *user)
{

  new_memo_header (course, key, from_prog, conf, user);
  if(paste)
     do_paste(user,conf);

}



int
main (void)
{
  char course[MAX_PATH + 1];	/* from crs=? command line */
  char key[MAX_KEY + 1];	/* from id=? command line */
  char from_prog[MAX_PATH + 1];	/* from from=? cmd line */
  int paste;			/* from [optional] paste=? command line */
  SESSION user;
  CONFIG_STRUCT conf;		/* the configuration read from config file */

  cs_cgi_init();

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

  if(!has_write_permission(&user, &conf))   /* shared_access.c */
       access_denied_error();

  set_discussion_names (conf.course_path, user.username, INTERNET_RESOURCES);
  display_new_memo_form (course, key, from_prog, paste, &conf, &user);

  cs_cgi_display("link_new_memo", 1);
  cs_cgi_destroy();
  return 0;
}

