/* -*-C-*-
*******************************************************************************
*
* File:         ComposeHelper.m
* RCS:          /usr/local/sources/CVS/EnhanceMail/ComposeHelper.m,v 1.3 1998/06/30 20:13:14 tom Exp
* Description:  
* Author:       Carl Edman
* Created:      Fri Oct 13 11:48:05 1995
* Modified:     Tue Jun 25 20:02:38 1996 (Carl Edman) cedman@capitalist.princeton.edu
* Language:     C
* Package:      N/A
* Status:       Experimental (Do Not Distribute)
*
* (C) Copyright 1995, but otherwise this file is perfect freeware.
*
*******************************************************************************
*/

#import "EnhanceMail.h"
#import "ComposeHelper.h"
#import "Preferences.h"
#import "PGP.h"
#import "regexp.h"

@implementation EnhanceComposeHelper

+ finishLoading:(struct mach_header *)header
{
   [NXApp addComposeHelperClass:self];
   return self;
}


- init
{
   if (self=[super init])
   {
      if (EnhanceUsePGP)
      {
	 char path[MAXPATHLEN];

	 if ([EnhanceBundle getPath:path forResource:"EncryptComposeHelper" ofType:"nib"])
	    [NXApp loadNibFile:path owner:self];

	 [encryptSwitch setState:EnhancePGPEncrypt];
	 [signSwitch setState:EnhancePGPSign];
      }
   }
   return self;
}

- (void)y2kFixDateHeader:(MailMessage *)mes
{
   static regexp *daterx;
   const char *date = [mes headerValueForKey:"Date"];

   if (!date) return;

   if (!daterx)
      daterx = regcomp("^( *[^ ,]+, *[ 0-9][0-9] +[^ ]+ )([0-9][0-9]+)( +.*)");

   if (regexec(daterx, date))
   {
      int year = atoi(daterx->startp[2]);

      if (year < 200)
      {
	 char subst[20];
	 char *fixedDate = alloca(daterx->endp[0] - daterx->startp[0] + 2 + 1);

	 if (year < 70) year += 2000; else year += 1900;

	 sprintf(subst, "\\1%d\\3", year);
	 regsub(daterx, subst, fixedDate);
	 [mes setHeaderKey:"Date" value:fixedDate];
      }
   }
}

- (View *)composeView
{
   if (EnhanceUsePGP) return accessoryBox;
   return nil;
}

- (BOOL)willDeliverMessage:(MailMessage *)mes to:(StringList *)rcpt
{
   if (EnhanceUsePGP)
   {
      BOOL shouldSign=[signSwitch state];
      BOOL shouldEncrypt=[encryptSwitch state];
      if ([[EnhancePGP new] encodePGP:mes to:rcpt sign:shouldSign encrypt:shouldEncrypt]==NO)
         return NO;
   }
   [self y2kFixDateHeader:mes];
   return YES;
}

@end // EnhanceComposeHelper
