package Platform::Email;
use strict;
use base qw( MIME::Lite );

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

  $args{From} ||= $Platform::CONFIG->{common}{email_from};

  {
    my @cc_list = @{$Platform::CONFIG->{common}{defined $args{alt_default_cc} ? $args{alt_default_cc} : 'email_cc'}};
    @cc_list = ( ) if delete $args{no_default_cc};

    if ($args{cc}) {
      if (ref $args{cc} eq 'ARRAY') {
        push @{$args{cc}},@cc_list;
      } else {
        $args{cc} = [ $args{cc},@cc_list ];
      }
    } else {
      $args{cc} = \@cc_list;
    }
  }

  $args{cc} = join(', ', @{$args{cc}}) if ref $args{cc} eq 'ARRAY';
  $args{Data} =~ s/\x{2019}/'/g;

  return $class->SUPER::new(%args);
}


sub send {
  my ( $self ) = @_;

  if (my $recipients = $Platform::CONFIG->{common}{rewrite_recipients}) {
    $self->add('X-Originally-To' => $self->get('To'));
    $self->add('X-Originally-cc' => $self->get('cc'));
    $self->replace('Subject' => $Platform::CONFIG->{common}{rewrite_recipients_subject}.$self->get('Subject'));

    $self->replace('To' => $recipients);
    $self->delete('cc');
  }

  my $rv;
  eval { $rv = $self->SUPER::send(@{$Platform::CONFIG->{common}{mailer}}); };
  if ($@) {
    warn Data::Dumper->Dump([$self]);
    warn $@;
  }

  return $rv;
}

1;
