package GUI::SWITCHUtil;
#<copyright>
# ----------------------------------------------------------
# Sun Proprietary/Confidential Code
# Copyright 2001, Sun Microsystems, Inc. All rights reserved.
# ----------------------------------------------------------
#</copyright>


use Roles;
use Util;
use strict 'vars';
use GUI::SAN;
use System;
use Data::Dumper;
use Agent::SWITCH;

sub get_list {
  my($q, $mult) = @_;
  my $L = Labels->read("GUI::Util")->section("fc");
  my($list);
  my($renv, $devs, $hosts,$notifs) = PDM::ConfigFile->read();
  my($first);
  $mult = "multiple size=$mult" if ($mult);
  my($allSW);
  if ($mult) {
     $allSW = "<select name=SW $mult>";
  } else {
     $allSW = "<select name=SW $mult><option value=\"\">$L->{select}</option>";
  }
  my %E;

  foreach my $d (@$devs) {
     if ($d->{class} =~ /switch/) {
       next if ($E{$d->{wwn}});
       $E{$d->{wwn}} = 1;
       $first  = "$d->{name}" if (!$first);
       my $sh = Util->shortHostname($d->{host}|| $renv->{hostname});
       $allSW .= ($d->{key} eq $q->{SW})? 
            "<option selected value=$d->{wwn}>$d->{name} /$sh":
            "<option value=$d->{wwn}>$d->{name} /$sh";
     }
  }
  $allSW .= "</select>";

  return $allSW;
}

sub cache {
  my($x, $q, $file) = @_;
  my($created, $reset, $VAR1);

  my($BDF) = System->get_home() . "/DATA/tmp/$file";

  if ($q->{ACTION_set}) {
     open(O, ">$BDF");
     print O Dumper($x);
     close(O);
  } elsif ($q->{ACTION_total}) {
     unlink $BDF;
  }

  if (-r $BDF) {
     open(O, $BDF); 
     my @a = <O>; close(O);
     eval "@a";
     $reset = $VAR1;
     $created = Util->get_file_created($BDF);
     my($hrs, $mins, $secs) = Util->getFileAge($BDF, "hms");
     $created = " <small>" . substr($created, 5) . " ( ${hrs}h ${mins}m ${secs}s</small>)";
  }
  return ($created, $reset);
}


sub fc_graph {
  my($q) = @_;
  my(%D, $applet, $x, $summ, @X, $xvalues, $reset, $created, $x0);
  my($title);
  my $L = Labels->read("GUI::Util")->section("fc");

  print Html->body();
  if ( my $deny = Roles->verifyRole($q, "expert") ) {
     print $deny;
 #    return;
  }

  my $mach ; # = Util->select_hosts("GUI::SWITCHUtil::fc_graph");
  my $hostname = System->shortHostname();
  print Html->header2("report.general.switch_graph", "99%" );

  my($debug) = 0;
  my($cache) = 0;
  my $Config = PDM::ConfigFile->read();
  my $error;
  my $allSW = &get_list($q, 0);
  my $dev;

   print "
    <table border=0><tr><td></table>
    <table border=0 cellspacing=0 cellpadding=0 width=100%><tr><td>
    <table border=0 cellspacing=0 cellpadding=0 width=100% bgcolor=black>
    <form method=get>
      <input type=hidden name=GO value=GUI::SWITCHUtil::fc_graph>
      <input type=hidden name=option value=9>
    <tr bgcolor=#666699>
       <td nowrap ><font color=white><b>
          &nbsp;$L->{select_sw}: $allSW 
          <input type=submit name=ACTION_display value=Display>&nbsp;$dev->{key}</td>
       <td nowrap align=right><b><font color=white>&nbsp;
          <input type=submit name=ACTION_set value=$L->{set}>
          <input type=submit name=ACTION_total value=$L->{total}>
       </td>
    </table></table>
    ";


  if ($q->{SW}) {
     $dev = $Config->deviceByWWN($q->{SW});
     $DB::single = 1;
     my($err2, $x, $data) = &FCfromDevice($dev);
     if ( $err2) {
          print "&nbsp;<p>";
          print Html->error($err2);
          return;
     }

     ($created, $reset) = &cache($x, $q, "SWFCgraph." . $dev->key());
     my($line, @b, @c,  $gc, $enc, $disk, @HBA, @ENC2);
  
     my $hbas = $x->{hba};
     my $encs = $x->{enc};
     my($y, $port);
  
     my $in;
     my $count = 0;
     foreach $y (sort keys %$data) {
       @c = split(/\|/, $y);
       $count++;
  
       $enc =  $c[0] . "|" . $c[1];
       $port = $c[2];
  
       $D{$enc}{$port} = $data->{$y};
       $in = 1;
     }

     for ($x0=1; $x0 <= $count; $x0++ ) {
        $xvalues .= "P$x0=Port $x0,";
     }

     $applet =<<EOF;
     <script>
     var a_width =  window.innerWidth - 45;
     var a_height =  window.innerHeight -140;
     window.document.writeln( 
          '<applet  $FC::APPLET height=' + a_height + ' width=' + a_width + '>');
     </script>

<param name=xTitle value="Switch Port">
<param name=nostyles value=0>
<param name=printCb value=1>
<PARAM name=backColor value="0,0,0">
<param name=showYvalues value=3>
<param name=browser value="sun">
<param name=fontsize value=11>
<param name=Yfontsize value=10>
<param name=minY value=0>
<param name=decimalsY value=-1>
<param name=hideXvalues value=0>
<param name=logY value=2>
<param name=gridCntY value=5>
<param name=vertSpace value=3>
<PARAM NAME=fontColor value="250,250,250">
<PARAM name=Grid value=1>
<param name=graphType value=40>
<param name=urlX value="$Http::WEBPROC?GO=GUI::SWITCHUtil::&fc_graph&">
<param name=urlY value="$Http::WEBPROC?GO=GUI::SWITCHUtil::&fc_graph&">
<param name=xurlTarget value="">
<param name=statusInfo value="select,disk,enclosure">
<param name=ySuffix value="">
<param name=hlColor value="250,250,100">
<PARAM name=xValues value="$xvalues">
EOF

#<xparam name=minX value=1>
#<xparam name=maxX value=9>
#<xparam name=urlColor value="white">
#<xparam name=maxY value=20>

     
     if (!$in) {
       print "<h2>No Device selected!";
       return;
     }
     my $stack_cnt = 1;
     $gc        = 1;
  
     foreach $enc (sort keys %D) {
       my(@c) = split(/\|/, $enc);
       my $enc0 =  $encs->{$c[1]};
  
       my $tit = $encs->{$c[1]};
       $applet .= "<param name=title$stack_cnt value=\"$enc0=$tit\">";
  
       my($seq_data, $link_data, $sync_data, $word_data, $crc_data, $sig_data, $port0, @reset1);
       my($in_data, $out_data);
  
       for ($port0=1; $port0 <= $count; $port0++) {
         $port = "port.$port0";
         my @new = split(/\t/, $D{$enc}{$port});
         @reset1 = split(/\t/, $reset->{data}{"$enc|$port|switch"});
  
         $link_data .= ($new[0] - $reset1[0]) . ",";   
         $sig_data  .= ($new[1] - $reset1[1]) . ",";   
         $seq_data  .= ($new[2] - $reset1[2]) . ",";   
         $crc_data  .= ($new[3] - $reset1[3]) . ",";   
         $sync_data .= ($new[4] - $reset1[4]) . ",";   # sync
         $word_data .= ($new[5] - $reset1[5]) . ",";   # word 
         $in_data   .= ($new[6] - $reset1[6]) . ",";  
         $out_data  .= ($new[7] - $reset1[7]) . ",";   
       }
       chop($sync_data); chop($word_data);
       chop($sig_data); chop($crc_data);
       chop($in_data); chop($out_data);

       $applet .= &applet_line("cyan", $gc, $link_data, "Link-Fail", $stack_cnt, 0);
       $gc++;
       $applet .= &applet_line("green",$gc, $sig_data, "Sig-Loss", $stack_cnt, 0);
       $gc++;
       $applet .= &applet_line("blue", $gc, $sync_data, "Sync-Loss", $stack_cnt, 1);
       $gc++;
       $applet .= &applet_line("red",  $gc, $word_data, "Inv TXWord", $stack_cnt, 1);
       $gc++;
       $applet .= &applet_line("yellow", $gc, $crc_data, "Inv-CRC", $stack_cnt, 1);
       $gc++;
       $applet .= &applet_line("white",  $gc, $seq_data, "Inv-Seq", $stack_cnt, 0);
       $gc++;
       $applet .= &applet_line("cyan",   $gc, $in_data, "In-Frame", $stack_cnt, 0);
       $gc++;
       $applet .= &applet_line("green",  $gc, $out_data, "Out-Frame", $stack_cnt, 0);
       $gc++;
       $stack_cnt++;
     }
     $applet .= "</applet>\n";
     if ($created) {
       $title = $L->expand(title3 => $created, $dev->{type}, $dev->{name});
     } else {
       $title = $L->expand(title4 => $dev->{type}, $dev->{name});
     }
  } else {
     $applet = "<b>$L->{nothing}<p>&nbsp;";
  }
  print "
    <table border=0 cellspacing=0 cellpadding=0 width=100% bgcolor=white>
    <tr><td colspan=2 nowrap>
         <center><table border=0><tr><td><b>&nbsp;$title</table></td>
    <tr><td></form></td>
    </table></table>";

  print "<table border=0 width=100% bgcolor=white><tr><td>$applet</table>";
  
}

sub applet_line {
  my($col, $gc, $data, $txt, $stack_cnt, $on) = @_;
  return "
    <param name=graphColor$gc value=\"$col\">
    <param name=graph$gc value=\"$data\">
    <PARAM name=label$gc value=\"$txt\">
    <PARAM name=yOffset$gc value=\"0\">
    <param name=active$gc value=$on>
    <param name=stack$gc value=\"$stack_cnt\">
   ";
}


sub FCfromDevice {
  my($dev) = @_;

  my $L = Labels->read("GUI::Util")->section("fc");
  my $agent = "Agent::" . uc($dev->{type});
  my $err1;
  if ( $err1= Modules->loadOne($agent)) {
       return ($L->expand(no_agent => $dev->{type},$dev->{name}));
  }
  #$agent .= "::new";
  #$agent = &$agent;

  if (!$agent->can("FCfromDevice")) {
       return ($L->expand(cannot_extract => $dev->{type}, $dev->{name}));
  }
  my $x = $agent->FCfromDevice($dev);
  my $data = $x->{data};
  my @K = keys %$data;
  if ($#K < 0) {
       return ($L->expand(cannot_extract => $dev->{type}, $dev->{name}));
  }
  return (undef, $x, $data);
}


sub fc_data {
  my($q) = @_;
  my(%D, $applet, $x, $summ, @X, $xvalues, $reset, $created, $title);

  my $L = Labels->read("GUI::Util")->section("fc");

  print "\n<body bgcolor=#E0E0E0><center>";
  if ( my $deny = Roles->verifyRole($q, "expert") ) {
     print $deny;
     return;
  }

  my $mach ; # = Util->select_hosts("GUI::SWITCHUtil::fc_data");
  my $hostname = System->shortHostname();
  print Html->header2("report.general.switch_data");
  
  my($debug) = 0;
  my($cache) = 0;
  my $Config = PDM::ConfigFile->read();

  my $allSW = &get_list($q);
  my $report;

  if ($q->{SW}) {
    my $dev = $Config->deviceByWWN($q->{SW});

    my($err2, $x, $data) = &FCfromDevice($dev);
    if ( $err2) {
          print "&nbsp;<p>";
          print Html->error($err2);
          return;
    }
  
    ($created, $reset) = &cache($x, $q, "SWFCdata." . $dev->key());

    my($line, @b, @c,  $gc, $enc, $disk, @HBA, @ENC2);
  
     my $encs = $x->{enc};
     my($y);
     my $hba_list;
  
  
     $report .= "Name         Component       Link       Sig       Seq       CRC      Sync    InvTxW  Inframes Outframes\n";
     $report .= "=" x 103 . "\n";
  
     my $data = $x->{data};
     
     foreach $y (keys %$data) {
       my(@c) = split(/\|/, $y);
       my(@d) = split(/\./, $c[2]);
       my $y2 = "$c[0]|$c[1]|$d[0].". sprintf("%2.2d", $d[1]) . "|$c[3]";
       $D{$y2} = $data->{$y};
     }
     my(@report);
     foreach $y (keys %$data) {
       my(@c) = split(/\|/, $y);
       my(@d) = split(/\./, $c[2]);
       if ($#d == 1) {
         $disk = $d[0] . "." . sprintf("%2.2d", $d[1]);
       } else {
         $disk = $c[2];
       }
  
       my @new = split(/\t/, $data->{$y});
       my @reset1 = split(/\t/, $reset->{data}{$y}) if ($reset);
       my(@y2) = ();
       my($pf, $y1);
       for ($y1=0; $y1 <= 7; $y1++) {
          my $dif = $new[$y1] - $reset1[$y1];
          if ($reset && $dif ) {
             push(@y2, "<b>$dif/</b>$new[$y1]");
             $pf .= "%17s";
          } else {
             push(@y2, "$new[$y1]");
             $pf .= "%10s";
          }
       }
       push(@report, sprintf("%-13s%-10s$pf\n", $encs->{$c[1]}, 
                     $disk, @y2));
  
     }
     my($last, $l);
     foreach $l (sort @report) {
       if (substr($l,0,10) ne $last) {
         $report .= "\n" if ($last); 
         $last = substr($l,0,10);
       }
       $report .= $l;
     }
     if ($created) {
       $title = $L->expand(title1 => $created);
     } else {
       $title = $L->{title2};
     }
   } else {
     $title = "<b>$L->{nothing}";
   }
   
   print "
    <table border=0><tr><td></table>
    <table border=0 cellspacing=0 cellpadding=4 width=95% bgcolor=white>
    <tr bgcolor=#666699>
       <td nowrap>
          <form> <input type=hidden name=GO value=GUI::SWITCHUtil::fc_data>
                 <input type=hidden name=option value=91>
          <font color=white><b>$L->{switch}: $allSW 
          <input type=submit name=ACTION_display value=$L->{display}>&nbsp; $q->{SW}</td>
       <td nowrap align=right><b><font color=white>&nbsp;
          <input type=submit name=ACTION_set value=$L->{set}>
          <input type=submit name=ACTION_total value=$L->{total}>
       </td>

    <tr> <td colspan=2><b>$title </b><br><pre>$report \n\n</td>

    </table></form>&nbsp;<p>&nbsp;";
}
  

1;
