package Common::Amazon::Mail;

use lib '/app/tools/common/lib';

use base 'Class::Accessor';

__PACKAGE__->mk_accessors(qw{html to from ses subject body file cc bcc list});

use strict;
use warnings;

use MIME::Entity;
use Net::AWS::SES::Signature4;

use Common::Amazon::Config;
use Common::Amazon::Mail::List;

sub new {
    my $class = shift;
    my $html  = shift;
    my ( $access, $secret, $region ) = get_aws_creds('sysmail');
    my $self = {
        'ses' => Net::AWS::SES::Signature4->new(
            'access_key' => $access,
            'secret_key' => $secret,
            'region'     => $region
        ),
        'list' => Common::Amazon::Mail::List->instance,
        'html' => defined $html ? 1 : 0,
    };
    bless $self, $class;
    $self;
}

#sub ses {
    #my $self = shift;
    #$self->{'ses'};
#}

sub maxsize {
    my $self = shift;
    my $max  = 2**20 * 10;
    $max;
}

sub sendit {
    my $self  = shift;
    my $files = shift;
    my $from  = defined $self->from ? $self->from : 'do-not-reply@royaltyshare.com';
    my $type  = $self->html ? 'text/html' : 'text/plain';

    # To prevent duplicate headers from being created,
    # we need to convert arrays into strings.
    my $to = $self->to;
    if (ref($to) eq 'ARRAY') {
        $to = join(',', @{$to});
    }

    my $cc = $self->cc;
    if (ref($cc) eq 'ARRAY') {
        $cc = join(',', @{$cc});
    }

    my $bcc = $self->bcc;
    if (ref($bcc) eq 'ARRAY') {
        $bcc = join(',', @{$bcc});
    }

    my $msg = MIME::Entity->build(
        'From'    => $from,
        'To'      => $to,
        'CC'      => $cc,
        'BCC'     => $bcc,
        'Subject' => $self->subject,
        'Data'    => $self->body,
        'Type'    => $type
    );

    if ( defined $files ) {
        foreach my $file ( @{$files} ) {
            $msg->attach(
                'Path'        => $file,
                'Disposition' => 'attachment'
            );
        }
    }

    my $response = $self->ses->send($msg);
    $response->is_success;

}

1;

