package Opals::Tb_Mail;

require Exporter;
@ISA       = qw(Exporter);

use Opals::Date qw(
    date_text
    date_DHM_text
);
# Version number
$VERSION   = 0.01;      

#use utf8;
use strict;
use MIME::Lite;

use Opals::Context;

sub new {

    my $class = shift;
    my (%param) = @_;
    my $dbh = $param{'dbh'};
    return unless $dbh;
    my $this = {
        dbh => $dbh,
    };
    bless $this,$class;
    return $this;

}

#===============================================================================

sub mail_send {

    my $this = shift;
    my ($params) = @_;
    my $preference = $params->{'pref'};
    my $to = $params->{'to'}; 
    my $cc = $params->{'cc'}; 
    my $subject = $params->{'subject'};
    my $data = $params->{'data'};
    my $eTxtContent = $params->{'eTextContent'};

    my $msg = MIME::Lite->new(
        From    => $preference->{'emailAddress'},
        To      => $to,
        Cc      => $cc,
        Subject => $subject,
        Data    => "$eTxtContent"
    );

    my $part = MIME::Lite->new(
        Type    => 'text/html',
        Data    => $data
    );
    $part->attr('content-type.charset' => 'UTF8');
    $msg->attach($part);

    my $retVal;
    if ($preference->{'emailSmtp'}) {
        if ($preference->{'emailUser'}) {
            $retVal = $msg->send(
                'smtp',
                $preference->{'emailSmtp'},
                AuthUser => $preference->{'emailUser'},
                AuthPass => $preference->{'emailPass'}
            );
        }
        else {
            $retVal = $msg->send(
                'smtp',
                $preference->{'emailSmtp'}
            ) or $retVal =0;
        }
    }
    else {
        $retVal = $msg->send;
    }
    return $retVal;
}

##===============================================================================
sub mail_sendQueuedMail{
    my $this = shift;
    my $dbh = $this->{'dbh'};
    my($params)=@_;
    my $emailList=$this->getContEmail();
    my $pref = $params->{'pref'};
    foreach my $email(@$emailList){
        my $status='sent';
        if($this->mail_validateEmail({email=>$email->{'email'}} )){       
            if(!$this->mail_send({  pref    => $pref,
                                    to      => $email->{'email'}, 
                                    cc      => $email->{'email_cc'}, 
                                    subject => $email->{'subject'}, 
                                    data    => $email->{'eContent'},
                                    eTxtContent=> $email->{'eTxtContent'} }) ){
                $status='fail';
            }
        }
        else{
            $status='rejected';
        }
        $this->updateEmailQueue({ eid=>$email->{'eid'}, status=>$status} );
    }
    return  $emailList;   
}

=item
#===============================================================================
sub mail_sendMails{
    my($dbh,$pref,$emailList)=@_;
    foreach my $email(@$emailList){
        my $status='sent';
        if(mail_validateEmail($email->{'email'},1)){
            if(!mail_send($pref,$email->{'email'}, $email->{'subject'}, $email->{'eContent'},$email->{'eTxtContent'})){
                $status='fail';
            }
        }
        else{
            $status='rejected';
        }

        updateEmailQueue($dbh,$email->{'eid'},$status);
    }
}
=cut
#===============================================================================
sub updateEmailQueue{
    my $this = shift;
    my $dbh = $this->{'dbh'};
    my ($params) = @_;
    my $eid = $params->{'eid'};
    my $status = $params->{'status'};

    if($status eq 'sent'){
        if( $dbh->do("select sendDate from  tb_emailRequest where eid=$eid  && (sendDate ='' or sendDate is null)")){
            $dbh->do("update tb_emailRequest set status ='$status',sendDate =now()   where eid=$eid ");
        }
        else{
            $dbh->do("update tb_emailRequest set status ='$status' , retryCount =retryCount +1 where eid=$eid ");
        }
    }
    else{
        $dbh->do("update tb_emailRequest set status ='$status' , retryCount =retryCount +1 where eid=$eid ");
    }
}

#===============================================================================
sub getContEmail{
    my $this = shift;
    my ($dbh) = $this->{'dbh'};
    my $sth = $dbh->prepare(<<_STH_);
select  r.eid,email,email_cc,subject,eContent,eTxtContent
from    tb_emailRequest r inner join tb_emailDetails d using(eid)       
where   (r.status = 'waiting' || r.status = 'rejected') 
        && ( retryCount =0 || (retryCount < 6 && sendDate + INTERVAL 3600 SECOND <=now())) 
order by eid 
_STH_
    
    my @eList=();
    $sth->execute();
    while (my $e = $sth->fetchrow_hashref) {       
        push @eList, $e ;
    }
    $sth->finish;
    return \@eList;

}

#===============================================================================
sub mail_validateEmail{
    my $this = shift;
    my ($params) = @_;
    my $email = $params->{'email'};
    my $checkHost = $params->{'checkHost'};
    if ($email !~ m/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/ &&
        $email =~ m/^.+\@((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))$/) {
        return (defined $checkHost && $checkHost ==1)? $this->validateHost($1):1;
    }
    else {
        return 0;
    }
}
#===============================================================================
sub validateHost{
    my $this = shift;
    my ($params) = @_;
    my $host= $params->{'host'};
    my $validHost=1;
    my $res = Net::DNS::Resolver->new();
    my $err=0;
    my @mx = mx($res, $host)
       or $validHost=0;

   return  $validHost;

}

1;
