package RT::Action::LightWeightSendMail;
require RT::Action::SendEmail;

use strict;
use vars qw/@ISA/;
@ISA = qw(RT::Action::SendEmail);

=head1 NAME

  RT::Action::LightWeightSendmail - An action which users can use to
  send mail out of RT (ex., in rt-crontool) without a RT::Transaction
  object.  It can be subclassed for more specialized mail sending
  behavior.

  You can pass it with an RT::Template object, but you can not use
  $Transaction in it because it's alwasy undef.

=cut

# {{{ sub Describe
sub Describe {
    my $self = shift;
    return (ref $self . " will send an email to ticket's owner.\n");
}

# }}}

# {{{ sub Prepare
sub Prepare {
    my $self = shift;
    # This actually populates the MIME::Entity fields in the Template Object
  
    unless ($self->TemplateObj) {
	$RT::Logger->warning("No template object handed to $self\n");
    }
  
    unless ($self->TicketObj) {
	$RT::Logger->warning("No ticket object handed to $self\n");
    }
  
  
    my ($result, $message) =
	$self->TemplateObj->Parse(Argument => $self->Argument,
				  TicketObj => $self->TicketObj);
  
    if ($result) {
	# Header
	$self->SetSubject();
	$self->SetSubjectToken();
	$self->SetRecipients();  
	$self->SetReturnAddress();
	$self->SetRTSpecialHeaders();
	if ($RT::EmailOutputEncoding) {
	    # l10n related header
	    $self->SetHeaderAsEncoding('Subject', $RT::EmailOutputEncoding);
	    $self->SetHeaderAsEncoding('From', $RT::EmailOutputEncoding);
	}
    }
  
    return $result;
  
}
# }}}

# {{{ sub Commit 
#Do what we need to do and send it out.
sub Commit {
    my $self = shift;

    # Go add all the Tos, Ccs and Bccs that we need to to the message to 
    # make it happy, but only if we actually have values in those arrays.
    
    $self->SetHeader('To', join(',', @{$self->{'To'}})) 
	if (@{$self->{'To'}});
    $self->SetHeader('Cc', join(',' , @{$self->{'Cc'}})) 
	if (@{$self->{'Cc'}});
    $self->SetHeader('Bcc', join(',', @{$self->{'Bcc'}})) 
	if (@{$self->{'Bcc'}});;

    my $MIMEObj = $self->TemplateObj->MIMEObj;
    $MIMEObj->make_singlepart;

    # try to convert message body from utf-8 to $RT::EmailOutputEncoding
    $self->SetHeader('Content-Type',
		     'text/plain;charset="utf-8"');
    RT::I18N::SetMIMEEntityToEncoding($MIMEObj,
				      $RT::EmailOutputEncoding);
    $self->SetHeader('Content-Type',
		     'text/plain;charset="'. $RT::EmailOutputEncoding .'"');

    #If we don't have any recipients to send to, don't send a message;
    unless ($MIMEObj->head->get('To') ||
	    $MIMEObj->head->get('Cc') || 
	    $MIMEObj->head->get('Bcc') ) {
	$RT::Logger->debug("$self: No recipients found. Not sending.\n");
	return(1);
    }

    # PseudoTo	(fake to headers) shouldn't get matched for message recipients.
    # If we don't have any 'To' header, drop in the pseudo-to header.
    $self->SetHeader('To', join(',', @{$self->{'PseudoTo'}}))
	if ( (@{$self->{'PseudoTo'}}) and (! $MIMEObj->head->get('To')));
    
    if ($RT::MailCommand eq 'sendmailpipe') {
	open (MAIL, "|$RT::SendmailPath $RT::SendmailArguments") || return(0);
	print MAIL $MIMEObj->as_string;
	close(MAIL);
    }
    else {
	my @mailer_args = ($RT::MailCommand);

        if ( $RT::MailCommand eq 'sendmail' ) {
	    push @mailer_args, $RT::SendmailArguments;
        }
        elsif ( $RT::MailCommand eq 'smtp' ) {
	    local $ENV{MAILADDRESS} = $RT::SMTPFrom || $MIMEObj->head->get('From');
	    push @mailer_args, (Server => $RT::SMTPServer);
	    push @mailer_args, (Debug => $RT::SMTPDebug);
        }
	else {
	    push @mailer_args, $RT::MailParams;
	}

        unless ( $MIMEObj->send( @mailer_args ) ) {
	    $RT::Logger->crit("$self: Could not send mail for ".$self->TransactionObj."\n");
            return (0);
        }
    }
    
    return (1);
}
# }}}

# {{{ Deal with message headers (Set* subs, designed for  easy overriding)

# {{{ sub SetRTSpecialHeaders

# This routine adds all the random headers that RT wants in a mail message
# that don't matter much to anybody else.

sub SetRTSpecialHeaders {
    my $self = shift;
    
    $self->SetReferences();

    $self->SetPrecedence();

    $self->SetHeader('X-RT-Loop-Prevention', $RT::rtname); 
    $self->SetHeader('RT-Ticket', $RT::rtname. " #".$self->TicketObj->id());
    $self->SetHeader
      ('Managed-by',"Request Tracker $RT::VERSION (http://www.fsck.com/projects/rt/)");

    return();
}

# }}}

# {{{ sub SetReturnAddress 

sub SetReturnAddress {
  my $self = shift;
  my %args = ( is_comment => 0,
	       @_ );

  # From and Reply-To
  # $args{is_comment} should be set if the comment address is to be used.
  my $replyto;

  if ($args{'is_comment'}) { 
      $replyto = $self->TicketObj->QueueObj->CommentAddress || 
		  $RT::CommentAddress;
  }
  else {
      $replyto = $self->TicketObj->QueueObj->CorrespondAddress ||
		  $RT::CorrespondAddress;
  }

  unless ($self->TemplateObj->MIMEObj->head->get('Reply-To')) {
      $self->SetHeader('Reply-To', "$replyto");
  }
}

# }}}

# {{{ sub SetSubject

sub SetSubject {
    my $self = shift;

    my $subject = $self->TemplateObj->MIMEObj->head->get('Subject') ||
	          $self->{'Subject'} ||
		  "An email from RT";
    $self->SetHeader('Subject', $subject);

    return $subject;
}

# }}}

eval "require RT::Action::LightWeightSendMail_Vendor.pm";
die $@ if ($@ && $@ !~ qr{^Can't locate RT/Action/LightWeightSendMail_Vendor.pm});
eval "require RT::Action::LightWeightSendMail_Local.pm";
die $@ if ($@ && $@ !~ qr{^Can't locate RT/Action/LightWeightSendMail_Local.pm});

1;
