###################################################################
# Copyright (C) 2006 RoyaltyShare, Inc.  All Rights Reserved
###################################################################

package Common::Email;

###
#   Common::Email
#
#   Updated to use Mail::Mailer as this provides us with better
#   diagnostics and doesn't rely on an SMTP server. The only
#   drawback is that it no longer works on Windows. This is fairly
#   acceptable though because we no longer work on Windows.
#
#   Usage:
#
#   Common::Email->Send( to      => 'me@there.com',
#                        from    => 'me@there.com',
#                        subject => "Test Message",
#                        body    => $testMessage );
#
#    Recipient list can be:
#        1. A single email address
#        2. A comma delimited string of email addresses
#        3. A list reference containing several email addresses
#
#    Die on all send mail errors.
###

use strict;
use warnings;
use Carp;

use Mail::Mailer;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Amazon::Mail;

sub new {
    my ( $class, %args ) = @_;
    my $self = bless {}, $class;

    return $self->_init(%args);
}

sub _init {
    my ( $self, %args ) = @_;
    my $stdout;
    my $stderr;

    $self->{_to}      = $args{to};
    $self->{_from}    = $args{from} || 'unknown@royaltyshare.com';
    $self->{_subject} = $args{subject} || "";
    $self->{_body}    = $args{body} || "";

    return $self;
}

sub Send {
    my ( $class, %args ) = @_;
    my $self = bless {}, $class;

    $self->_init(%args);

    assert( $self->{_to} );
    assert( $self->{_subject} );
    assert( $self->{_body} );

    my ($mailer) = new Mail::Mailer qw(sendmail);

    my (%headers) = (
        'From'    => $self->{_from},
        'To'      => $self->{_to},
        'Subject' => $self->{_subject}
    );

    my $body = $self->{_body};

    $mailer->open( \%headers );
    print $mailer $body;
    $mailer->close;

    return $self;
}

sub SendAWS {
    my ( $class, %args ) = @_;
    my $self = bless {}, $class;

    $args{from} = defined $args{from} ? $args{from} : 'do-not-reply@royaltyshare.com';

    $self->_init(%args);

    assert( $self->{_to} );
    assert( $self->{_subject} );
    assert( $self->{_body} );

    my $mail = Common::Amazon::Mail->new;
    $mail->to( $self->{_to} );
    $mail->from($self->{_from});
    $mail->subject( $self->{_subject} );
    $mail->body( $self->{_body} );
    $self->{_response} = $mail->sendit;

    return $self;

}

1;
