package Mail;

# This file only has SendUpdateConfirmation in it.  It generates a
# mail message to send to both competitors in a couple when their
# registration changes.

sub SendUpdateConfirmation {

  my $mail_ref=$_[0];
  my ($date, $day, $month, $date, $timestamp, $est, $year, @mailfile,
      $i, $mailto, @mailcmd, $leader, $follower);
  
  $leader=shift(@$mail_ref);
  $follower=shift(@$mail_ref);

  if ($leader->doesEmailExist() && $follower->doesEmailExist()) {
    $mailto=$leader->getEmail().", ".$follower->getEmail();
  } elsif ($leader->doesEmailExist()) {
    $mailto=$leader->getEmail();
  } elsif ($follower->doesEmailExist()) {
    $mailto=$follower->getEmail();
  } else {
    return;
  }

  $date=&main::ctime(time);
  ($day, $month, $date, $timestamp, $est, $year)=split(' ', $date);
  
  open(MAIL_HEAD, Constants::get("MAIL_HEAD")) ||
    Error::CantOpenFile(Constants::get("MAIL_HEAD"));
  open(MAIL_TAIL, Constants::get("MAIL_TAIL")) ||
    Error::CantOpenFile(Constants::get("MAIL_TAIL"));

  push(@mailfile, "To: $mailto\n");
  push(@mailfile, "From: \"".Constants::get(REGISTRAR_TITLE).
       "\" <".Constants::get(REGISTRAR_EMAIL).">\n");
  push(@mailfile, "Subject: ".Constants::get(MAIL_SUBJECT)."\n");
  push(@mailfile, "-------\n");

  while(<MAIL_HEAD>) {
    push(@mailfile, $_);
  }
  close(MAIL_HEAD);

  push(@mailfile, "\t".Constants::get(HTML_MSG3)."\n");
  push(@mailfile, Constants::get(HTML_MSG5).": ".$leader->getName()."\n");
  if ($leader->doesEmailExist()) {
    push(@mailfile, Constants::get(HTML_MSG6).": ".$leader->getEmail()."\n");
  } else {
    push(@mailfile, Constants::get(HTML_MSG6).": ".
      Constants::get(HTML_MSG18));
  }
  push(@mailfile, Constants::get(HTML_MSG7).": ".$leader->getSchool()."\n");
  push(@mailfile, "\n");
  push(@mailfile, "\t".Constants::get(HTML_MSG4)."\n");
  push(@mailfile, Constants::get(HTML_MSG5).": ".$follower->getName()."\n");
  if ($follower->doesEmailExist()) {
    push(@mailfile, Constants::get(HTML_MSG6).": ".$follower->getEmail()."\n");
  } else {
    push(@mailfile, Constants::get(HTML_MSG6).": ".
      Constants::get(HTML_MSG18));
  }
  push(@mailfile, Constants::get(HTML_MSG7).": ".$follower->getSchool()."\n");
  push(@mailfile, "\n");

  for ($i=0;$i<=$#$mail_ref;$i++) {
    push(@mailfile, "\t$$mail_ref[$i]\n");
  }

  while(<MAIL_TAIL>) {
    push(@mailfile, $_);
  }
  close(MAIL_TAIL);

  $mailto=~s/@/\\@/g;
  General::log("sending mail to '$mailto'");

  $mailcmd=Constants::get("MAILCMD")." $mailto";
  General::log("mailcmd=$mailcmd, sizeof mailfile=$#mailfile");
  &main::open2(RDR, WTR, "$mailcmd") ||
    Error::Croak("Couldn't send mail: '$mailcmd'!");

  for ($i=0;$i<=$#mailfile;$i++) {
    General::log("mail: $mailfile[$i]");
    print WTR $mailfile[$i];
  }
  close(RDR);
  close(WTR);
}

1;
