package XXV::OUTPUT::NEWS::MAIL;
use strict;

use Tools;
use Locale::gettext;
use Mail::SendEasy;

# News Modules have only this methods
# init - for intervall or others
# send - send the informations
# read - read the news and parse it
# req  - read the actual news print this out

# This module method must exist for XXV
# ------------------
sub module {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $args = {
        Name => 'NEWS::MAIL',
        Description => gettext('This NEWS module generate mails for news.'),
        Version => '0.01',
        Date => '31.09.2005',
        Author => 'xpix',
        Preferences => {
            active => {
                description => gettext('Activate this service'),
                default     => 'n',
                type        => 'confirm',
                required    => gettext('This is required!'),
            },
            interval => {
                description => gettext('Time in hours to send the next mail'),
                default     => 12,
                type        => 'integer',
                required    => gettext('This is required!'),
            },
            address => {
                description => gettext('One or more mail addresses for sending the news'),
                default     => 'unknown@example.com, everybody@example.com',
                type        => 'string',
                required    => gettext('This is required!'),
            },
            smtp => {
                description => gettext('Hostname from SMTP mail server'),
                default     => main::getModule('STATUS')->name,
                type        => 'string',
                required    => gettext('This is required!'),
            },
            susr => {
                description => gettext('Username for mail server access'),
                default     => 'xxv',
                type        => 'string',
            },
            spwd => {
                description => gettext('Password for mail server access'),
                default     => 'xxv',
                type        => 'password',
                check       => sub{
                    my $value = shift || return;

                    return $value unless(ref $value eq 'ARRAY');

                    # If no password given the take the old password as default
                    if($value->[0] and $value->[0] ne $value->[1]) {
                        return undef, gettext("Field with 1st and 2nd password must be equal to confirm!");
                    } else {
                        return $value->[0];
                    }
                },
            },
        },
    };
    return $args;
}

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

    # paths
    $self->{paths} = delete $attr{'-paths'};

	# who am I
    $self->{MOD} = $self->module;

    # host
    $self->{host} = delete $attr{'-host'};

    # all configvalues to $self without parents (important for ConfigModule)
    map {
        $self->{$_} = $attr{'-config'}->{$self->{MOD}->{Name}}->{$_} || $self->{MOD}->{Preferences}->{$_}->{default}
    } keys %{$self->{MOD}->{Preferences}};

    # create Template object
    $self->{tt} = Template->new(
      START_TAG    => '\<\?\%',		    # Tagstyle
      END_TAG      => '\%\?\>',		    # Tagstyle
      INTERPOLATE  => 1,                # expand "$var" in plain text
      PRE_CHOMP    => 1,                # cleanup whitespace
      EVAL_PERL    => 1,                # evaluate Perl code blocks
      ABSOLUTE     => 1,
    );

    # The Initprocess
    my $erg = $self->init or return error('Problem to initialze News Module');

    $self->{TYP} = 'text/plain';

	return $self;
}

# ------------------
sub init {
# ------------------
    my $obj = shift || return error ('No Object!' );

    $obj->{LastReportTime} = time;

    # Interval to send the next mail
    Event->timer(
        interval => $obj->{interval}*3600,
        prio => 6,  # -1 very hard ... 6 very low
        cb => sub{
            $obj->send();
        },
    );

    $obj->{MAIL} = Mail::SendEasy->new(
        smtp => $obj->{smtp},
        user => $obj->{susr},
        pass => $obj->{spwd},
    ) || return error($Mail::SendEasy::ER);

    my @tmplfiles = glob(
        sprintf('%s/%s_*.tmpl',
            $obj->{paths}->{NEWSTMPL},
            lc((split('::', $obj->{MOD}->{Name}))[-1])
        )
    );
    for (@tmplfiles) {
        my ($order, $typ) = $_ =~ /_(\d+)_(\S+)\.tmpl$/si;
        $obj->{TEMPLATES}->{$typ} = $_;
    }

    1;
}

# ------------------
sub send {
# ------------------
    my $obj = shift  || return error ('No Object!' );

    return undef, lg('This function is deactivated!')
        if($obj->{active} ne 'y');

    return undef, lg('The newsstack is empty!')
        unless($obj->{NEWSLETTER});

    ++$obj->{COUNT};

    my $content = $obj->req();

    my $smod = main::getModule('STATUS');
    my @addresses = split(/\s*,\s*/, $obj->{address});

    # Send mail
    my $status = $obj->{MAIL}->send(
        from    => sprintf('%s@%s.de', 'xxv', $smod->name),
        from_title => 'XXV MailNewsAgent',
        to      => shift @addresses ,
        cc      => join(',', @addresses),
        subject => "News from your XXV System!" ,
        msg     => $content,
        msgid   => $obj->{COUNT},
    ) || return error($obj->{MAIL}->error);

    $obj->{LastReportTime} = time;

    lg sprintf('News Mail with nr. %d succesfully send at %s', $obj->{COUNT}, scalar localtime);
    $obj->{NEWSLETTER} = undef;
    1;
}

# ------------------
sub parseHeader {
# ------------------
    my $obj = shift  || return error ('No Object!' );
    my $output = '';

    my $vars = {
        msgnr => $obj->{COUNT},
        date  => datum(time, 'voll'),
        anzahl=> $obj->{NEWSCOUNT},
    };

    my $template = $obj->{TEMPLATES}->{'header'};
    $obj->{tt}->process($template, $vars, \$output)
          or return error($obj->{tt}->error());

    return $output;
}

# ------------------
sub parseFooter {
# ------------------
    my $obj = shift  || return error ('No Object!' );
    my $output = '';


    my $vars = {
        usage => main::getModule('RECORDS')->{usage},
        uptime  => main::getModule('STATUS')->uptime,
        lastreport => datum($obj->{LastReportTime}, 'voll'),
    };

    my $template = $obj->{TEMPLATES}->{'footer'};
    $obj->{tt}->process($template, $vars, \$output)
          or return error($obj->{tt}->error());

    return $output;
}


# ------------------
sub read {
# ------------------
    my $obj = shift  || return error ('No Object!' );
    my $vars = shift || return error ('No News!' );
    my $output = '';

    $vars->{count} = ++$obj->{NEWSCOUNT};
    $vars->{host}  = $obj->{host};
    $vars->{port}  = main::getModule('HTTPD')->{Port};

    my $template = $obj->{TEMPLATES}->{'content'};
    $obj->{tt}->process($template, $vars, \$output)
          or return error($obj->{tt}->error());

    $obj->{NEWSLETTER} .= $output;

    return $output;
}

# ------------------
sub req {
# ------------------
    my $obj = shift  || return error ('No Object!' );
    my $content = '';

    $content .= $obj->parseHeader();
    $content .= $obj->{NEWSLETTER};
    $content .= $obj->parseFooter();

    return $content;
}


1;
