#!/usr/bin/perl -w

# Trida pro odesilani emailu

package temail;

use Time::Local;

sub new {
  my ($type,$dbconn)=@_;
  $dbh=$dbconn;
  my ($self)={};
  bless($self,$type);
  return($self);
}

sub sendmail {
  my ($self, $id, $text) = @_;
  my ($timestamp, $sql, $mesic, @result, @data);
  @cas=localtime(time);
  $cas[4]+=1;
  $cas[2]=$self->zerofill($cas[2]);
  $cas[1]=$self->zerofill($cas[1]);
  $timestamp="$cas[3].$cas[4]. $cas[2]:$cas[1]";
  $sql=$dbh->prepare("SELECT name FROM node WHERE id=$id");
  $sql->execute or die("SQL error");
  @result=$sql->fetchrow_array;
  $sql=$dbh->prepare("SELECT email FROM node_email WHERE id=$id");
  $sql->execute or die("SQL error");
  while(@data=$sql->fetchrow_array) {
    system("mail -s '$text: $result[0] $timestamp' '$data[0]' < /dev/null");
  }
}


# doplneni numerickeho reteze o nulu, pokud je <=9
sub zerofill {
  my ($self, $vstup) = @_;
  if($vstup =~ /^\d{1}$/) { return("0$vstup"); } else { return($vstup); }
}


return(1);