package Reports;
use strict 'vars';
use Mail;

sub email {
  my($class, $q, $email, $title, $LIST) = @_;

  my ($s,$x);
  for ($x=0; $x <= $#$LIST; $x++) {
     $s++ if ($q->{"email_$x"});
  }
  my $LB = Labels->read("Reports");
  if (!$q->{email}) {
     print Html->warning($LB->{enter});
  } elsif (!$s) {   
     print Html->warning($LB->{enter2});
  } else {
    my (@L);
    for ($x=0; $x <= $#$LIST; $x++) {
       my $el = $LIST->[$x];
       my $fn = $el->[1];
       my $data =  &$fn($q);
       $data =~ s/<img /<ximg /g;
       push(@L, $el->[0], $data, "html")  if ($q->{"email_$x"});
    }
    my $data = Util->email_html("Storage_ADE", $title, $email, "$title from StorADE", @L);
    Mail->mailData($email, $data);
  }
}

#  LIST = [ [html_name, function, title], ... ...]
sub list {
 my($class, $q, $LIST, $last_run) = @_;
 my ($x);
 my $notifs = System->get_configNotifs();

 my $LB = Labels->read("Reports");
 my (@array);
  for ($x=0; $x <= $#$LIST; $x++) {
    my $el = $LIST->[$x];
    my ($url, $ck, $txt_url);
    if ($last_run) {
      $url = "<a href=$Http::WEBPROC?GO=$el->[1]>$el->[2]</a>";
      $ck =  "<input type=checkbox name=email_$x>";
      $txt_url = "| <a href=$Http::WEBPROC?GO=$el->[1]&text=1>$LB->{csv}</a>"
                if (0);
    }
    push(@array, [$ck, $url, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ]);
  }

  my $email1 = $q->{email} || $notifs->[0]{email};

  my $scr = Html::Screen->new();  
  $scr->list($q, { pageInfo => 0 , bottomButton => 1 },
  [ 
  [ c => $LB->{select}  ],
  [ l => $LB->{display} ],
  [ l => "" ],
  ],
  \@array,
  [
  [ l => 'ACTION_email', $LB->{submit}, !$last_run ],
  [ l => 'DATA', "&nbsp;$LB->{enter4}:<input type=text name=email size=40 value=\"$email1\">"],
  ]);

  return $scr->out();
}


sub format {
  my($class, $q, $REP, $out, $no_scheduler) = @_;
  my $header;
  my $G = Labels->read();

  if ($q->{text}) {
     $header = Html->text_header(0,"Content-type: text/csv\nLocation: frureport.csv");
     $$out = "";
     foreach my $l (@$REP) {
        $$out .= join("\t", @$l) . "\n";
     }
     print $header . $$out;
     return;
  }

  $header = Html->body();

  if ($q->{email}) {
    return $header . $$out;
  } else {
    print $header  . $$out;
    return undef;
  }
}

sub schedule {
  my($class, $q, $no_scheduler) = @_;

  my $G = Labels->read();
  if (!$q->{email} && !$no_scheduler) {
    my $l;
    foreach my $e (keys %$q) {
       my $e1 = $e;
       $e1 = "_GO" if ($e1 eq "GO");
       $l .= "$e1=$q->{$e}&" if ($q->{$e});
    }
     my $js = "<script>
  function sched(a) {
     var b = '$Http::WEBPROC?GO=GUI::Scheduler::add&$l';
     var O = window.open(b,'hist','menubar=no,resizable=yes,scrollbars=yes,width=500,height=300');
      O.focus();
  }
  </script>
    ";
    $js .= "[ <a href=javascript:sched(0)>$G->{schedule_report}</a> ]";
    return $js;
  }
}

1;


