#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>


#include "../global.h"

#include "shared_util.h"
#include "shared_lock.h"
#include "shared_cs_util.h"
#include "shared_news_util.h"
#include "shared_bio.h"

static void
read_post_newfile (const char *new_fname, NEWFILE_RECORD * new_info)
{
  FILE *new_fp;

  new_fp = fopen (new_fname, "r");
  if (!new_fp)
    cs_critical_error (ERR_UNABLE_TO_OPEN_NEW_FILE, "");
  if (fread (new_info, sizeof (NEWFILE_RECORD), 1, new_fp) != 1)
    cs_critical_error (ERR_ERROR_READING_NEW_FILE, "");
  fclose(new_fp);  
}





void
add_new_post_msg (NEWFILE_RECORD * new_info, const char *inbox_fname)
{
  FILE *fp;
  INBOX_RECORD record;

  fp = fopen (inbox_fname, "a");
  if (!fp)
    cs_critical_error (ERR_UNABLE_TO_OPEN_INBOX, "");
  
  get_exclusive_lock(fileno(fp), 1);   /* shared_lock.c */
  record.newfile_info = *new_info;
  record.time_read = 0;
  record.is_sleepy = 0;


  if (fwrite (&record, sizeof (INBOX_RECORD), 1, fp) != 1)
    cs_critical_error (ERR_ERROR_WRITING_TO_INBOX, "");
  release_lock(fileno(fp));   /* shared_lock.c */  
  fclose (fp);
}





static void
process_post_new_file (const char *new_fname, const char *inbox_fname)
{
  NEWFILE_RECORD newfile_info;

  read_post_newfile (new_fname, &newfile_info);
  add_new_post_msg (&newfile_info, inbox_fname);
}





void
update_post_inbox (const char *username, CONFIG_STRUCT *conf)
{
  DIR *dir_p;
  struct dirent *dir_entry_p;
  char *ptr;
  char mail_dir[MAX_PATH + 1];
  char new_fname[MAX_PATH + 1];
  char inbox_fname[MAX_PATH + 1];

  snprintf (mail_dir, MAX_PATH + 1, "%s%s/%s/%s", conf->course_path, PEOPLE_DIR, username, MAIL_DIR);
  snprintf (inbox_fname, MAX_PATH + 1, "%s/%s", mail_dir, INBOX_FNAME);
  dir_p = opendir (mail_dir);
  if (!dir_p)
    cs_critical_error (ERR_CANT_OPEN_NEWS_DIR, "");


  while (NULL != (dir_entry_p = readdir (dir_p)))
    {
      ptr = strstr (dir_entry_p->d_name, ".new");
      if (ptr && *(ptr + 4) == '\0')	/* i.e. if file ends in .new */
	{
	  snprintf (new_fname, MAX_PATH + 1, "%s/%s", mail_dir,
		    dir_entry_p->d_name);
	  process_post_new_file (new_fname, inbox_fname);
	  unlink (new_fname);

	}

    }
  closedir (dir_p);
}




static
void  set_msg_value(int index, char *name, char *value)
{
#define MAX_TMP_NAME 50
char the_name[MAX_TMP_NAME + 1];

 if(index < 0)
   snprintf(the_name, MAX_TMP_NAME + 1, "msg.%s", name);
 else
   snprintf(the_name, MAX_TMP_NAME + 1, "msg.%d.%s", index, name);
  
 cs_set_value(the_name, value);

#undef MAX_TMP_NAME
}


static int
multiple_recipients (SESSION *user, PERSON_NODE *pers_head)
{
  PERSON_NODE *pptr;

  for (pptr = pers_head; pptr; pptr = pptr->next)
    if (((pptr->data.how_received == CC) || (pptr->data.how_received == TO))
	&& strcmp (user->username, pptr->data.username))
      return 1;

  return 0;
}





void
set_inbox_msg_header_data (INBOX_RECORD * inbox,
		           char *course,  char *key,
		           int website_attached, long offset,
                           CONFIG_STRUCT *conf, SESSION *user, 
                           ATTACHMENT_NODE *attach_head,
                           PERSON_NODE *pers_head, int index)
{
  #define MAX_TMP_NAME 30
  ATTACHMENT_NODE *aptr;
  PERSON_NODE *pptr;
  char timestring[MAX_TIMESTRING + 1];
  int i;
  char extension[MAX_FILENAME + 1];
  char name[MAX_TMP_NAME];
  char url[MAX_PATH * 2];
  char *escaped_subject = 0;
  

  /* time the user running this program first opened this message */
  strftime (timestring, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT, localtime (&inbox->time_read));
  set_msg_value(index, "time_read", timestring);

  /* did the user mark this message as 'sleepy' or 'hidden' ? */
  set_msg_value(index,"is_user_hidden", inbox->is_sleepy? "1": "0");
  
  
  /* username of person who wrote the message */
  set_msg_value(index, "sender", inbox->newfile_info.sender);
  
  /* real name of person who wrote the message */
  set_msg_value(index, "sender_realname",  inbox->newfile_info.sender_realname);


  /* set a 'has_multiple_recipients' value to help with decision about
  ** whether or not to include a group reply button 
  **/
  
  if(multiple_recipients(user, pers_head))
    set_msg_value(index, "has_multiple_recipients",  "1");
     
     
     
/* The 'how_sent' value shouldn't be needed, but we'll set values
** for this enumerated type anyway
**/      
  switch(inbox->newfile_info.how_sent)
  {
   case NEWMSG: set_msg_value(index, "how_sent", "NEWMSG"); break;
   case FORWARD: set_msg_value(index, "how_sent", "FORWARD"); break;   
   case REPLY: set_msg_value(index, "how_sent", "REPLY"); break;   
   case GROUP_REPLY: set_msg_value(index, "how_sent", "GROUP_REPLY"); break;   
   case 4: set_msg_value(index, "how_sent", "DELETED"); break;        /* because DELETED exists *twice* in global.h */
   default:  set_msg_value(index, "how_sent", "unknown"); break;
  }



/* The 'how_received' value shouldn't be needed, and may not even be used at all within
** recent versions of Manhattan, but we'll set values for this enumerated type anyway
**/      
  switch(inbox->newfile_info.how_received)
  {
   case TO: set_msg_value(index, "how_received", "TO"); break;
   case CC: set_msg_value(index, "how_received", "CC"); break;   
   case BCC: set_msg_value(index, "how_received", "BCC"); break;   
   default:  set_msg_value(index, "how_received", "unknown"); break;
  }


  /********* Subject provided in both 'raw' and html escaped versions */
  set_msg_value(index, "subject", inbox->newfile_info.subject);
  
  escaped_subject = (char *) 0;
  cs_html_escape_string(inbox->newfile_info.subject, &escaped_subject);   /* shared_cs_util.c */
  if(escaped_subject)
      {
        set_msg_value(index, "escaped_subject", (char *) escaped_subject);
        free(escaped_subject);
        escaped_subject = (char *) 0;
       } 
  else /* should never happen */
      set_msg_value(index, "escaped_subject", inbox->newfile_info.subject);


  /* time the message was sent */
  strftime (timestring, MAX_TIMESTRING, DOW_DATE_TIME_FORMAT,
	    localtime (&inbox->newfile_info.time_sent));
  set_msg_value(index, "time_sent", timestring);

  /* how many attachments are there? */
  snprintf(url, MAX_PATH * 2, "%d", inbox->newfile_info.attachments);
  set_msg_value(index,"attachments", url);
  
  /* name of the 'info' file */
  set_msg_value(index, "info_fname", inbox->newfile_info.info_fname);


  /* offset value */
  snprintf(timestring, MAX_TIMESTRING, "%ld", offset);  
  set_msg_value(index, "offset", timestring);
  

 /******** To: list ********/
  for ( i = 0, pptr = pers_head; pptr; pptr = pptr->next)
    if (pptr->data.how_received == TO)
      {
        snprintf(name, MAX_TMP_NAME, "to.%d", i);
	set_msg_value(index, name, pptr->data.realname);
	i++;
      }

  snprintf(url, MAX_PATH * 2, "%d", i);
  set_msg_value(index, "to_count", url);  /* provide a count of 'to' recipients */


 /******** CC list *********/
  for ( i = 0, pptr = pers_head; pptr; pptr = pptr->next)
    if (pptr->data.how_received == CC)
      {
        snprintf(name, MAX_TMP_NAME, "cc.%d", i);
	set_msg_value(index, name, pptr->data.realname);
	i++;
      }
  snprintf(url, MAX_PATH * 2, "%d", i);
  set_msg_value(index, "cc_count", url);  /* provide a count of 'cc' recipients */


 
  if (website_attached)
    {
      set_msg_value(index, "website_attached", "1");
      
      snprintf(url, MAX_PATH *2, 
	"%s?crs=%s&amp;id=%s&amp;sender=%s&amp;inf=%s&amp;grp=%d&amp;read=%d&amp;loc=%ld&amp;inbox=yes&amp;from=post_read_inbox",
                 "web_page_start",
                 course,
                 key,
                 inbox->newfile_info.sender,
                 inbox->newfile_info.info_fname,
                 MAIL,
                 inbox->time_read? 1: 0,
                 offset);

       set_msg_value(index, "website_url", url);
      
         
    }
  else
		   /***** attachments ***/ 
    if (attach_head)
    {
     /* note the ext=<file_extension> parameter isn't used by the send_file program
     ** it's there to help offline browser programs to determine the type of file
     ** being sent
     */
      i =0;
      for (aptr = attach_head; aptr; aptr = aptr->next)
      {
        get_extension(aptr->data.orig_fname, extension);   /* shared_news_util.c */
        
        snprintf(name, MAX_TMP_NAME, "file.%d.url", i);
	snprintf
	  (url, MAX_PATH*2, "%s?crs=%s&amp;id=%s&amp;user=%s&amp;fname=%s&amp;info=%s&amp;attach=%d&amp;ext=.%s",
	   "send_file", course, key, inbox->newfile_info.sender,
	   aptr->data.unique_fname, inbox->newfile_info.info_fname,
	   inbox->newfile_info.attachments, extension);
	set_msg_value(index, name, url);
	
        snprintf(name, MAX_TMP_NAME, "file.%d.orig_fname", i);
        set_msg_value(index, name, aptr->data.orig_fname);
	
	
        /* if this is an mp3 file
        ** provide url for mp3 player
        */
        if(!strcmp(extension,"mp3"))   /* custom.h */
	{
         
	      cs_set_server_name();
	      snprintf(url, MAX_PATH +1, "podcast_launch_framaplayer?crs=%s&id=%s&title=%s&sender=%s&fname=%s&inf=%s&grp=%d&realname=%s",
	        course, key, inbox->newfile_info.subject, inbox->newfile_info.sender, aptr->data.unique_fname,
               inbox->newfile_info.info_fname, MAIL, inbox->newfile_info.sender_realname);

           snprintf(name, MAX_TMP_NAME, "file.%d.wimpy_button_url", i);
           set_msg_value(index, name, url);
        }	  
	i++;
      }
    }

  #undef MAX_TMP_NAME 





















}
