# Contents
# - showReadingLevel
# - yearToYearMonth
# - scoreToGrade

%lex = ( 'Reading Level' => 'Reading Level',
	 'Name' => 'Name',
	 'Date' => 'Date',
	 'Tot' => 'Tot',
	 'EGr' => 'EGr',
	 'Error' => 'Error',
    );

    
#-------------------
sub showReadingLevel {
#-------------------
    my ( $readinglevel, $onlylatest, $stud_ref, $startdate, $enddate,
	 $sortorder,$dratype,$bktype, $dbh ) = @_;
    
    # Reading tests are distinguished by reading level, but also book
    # type (fiction / nonfiction) where dra2 didn't have a book type and also
    # as well as a dratype (DRA 2 or DRA 3).

#    print "Book Type:$bktype<br>\n";
    
    my $helptable = 'read_level_dra2'; # the table holding the help information (dra2 or dra3)
    if ( $dratype == 3 ) {
	$helptable = 'read_level_dra3';
    }
    
    if ( $sortorder eq 'ascending' ) {
	$sortorder = ''; # normal ascending sort; blank
    } else {
	$sortorder = 'desc'; # descending sort; this is for SQL.
    }
    
    my @students = @$stud_ref;


    
    # Get reading score objectives (not scores yet) from the first record scores table.
    my %objectives; # from read_level_dra2 or 3.
    my $sth;
    if ( $dratype == 2 ) {
	$sth = $dbh->prepare("select name, category, seq from $helptable
			     where readlevel = ?"); # no worries from fic/nonfiction
	$sth->execute( $readinglevel );
    } else { # dratype is 3
	$sth = $dbh->prepare("select name, category, seq from $helptable
			     where readlevel = ? and bktype = ?"); # no worries from fic/nonfiction
	$sth->execute( $readinglevel, $bktype);
    }
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    while ( my ( $name, $category, $seq ) = $sth->fetchrow ) {
	$objectives{ $seq } = $category. '::'. $name;
    }


    # Set Index values for all objectives
    my $count = 0;
    my $startcount;
    my %skip;
    my $currcat = '';

   # Print out First Heading Line
    my $colspan = 4;
    print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin-bottom:2em;">\n};
    print qq{<tr><th colspan="$colspan">$lex{'Reading Level'} $readinglevel DRA$dratype $bktype</th>\n};


    foreach my $key ( sort { $a <=> $b } keys %objectives ) { # numeric sort 

	my ( $category, $name ) = split(/::/, $objectives{$key} );
	$oldcat = $currcat;
	$currcat = $category;

	if ( $oldcat ne $currcat and $count ) {
	    $diff = $count - $startcount;
	    print qq{<th colspan="$diff" style="font-size:100%;">$oldcat</th>\n};
	    $skip{$oldcat} = $diff;
	    $startcount = $count;

	}
	
	$count++;

    }
    $diff = $count - $startcount;
    $skip{$currcat} = $diff;
    print qq{<th colspan="$diff" style="font-size:100%;">$currcat</th></tr>\n};


    # Print Out Second Heading Line
    print qq{<tr><th>$lex{Name}</th><th>$lex{Date}</th><th>$lex{Tot}</th><th>$lex{EGr}</th>\n};

    # SQL Query of global reading level table.
    my $sth1 = $dbh->prepare("select id, help1 from $helptable where readlevel = ? and
      category = ? and name = ?");

    foreach my $key ( sort { $a <=> $b } keys %objectives ) { # numeric sort 
	my ( $category, $name ) = split(/::/, $objectives{$key} );
	
	# Get the record id and help for this...
	$sth1->execute( $readinglevel, $category, $name );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($id, $help1 ) = $sth1->fetchrow;

	print qq{<th class="fs6">};
	if ( $help1 ) {
	    print qq{<a href="javascript:showhelp($id,$dratype)">};
	    print qq{&#9405; $name</a>};
	} else {
	    print qq{$name};
	}
	print qq{</th>\n};

    }
    print qq{</tr>\n};


    # Now loop through all students printing results; setup queries first
    my $sth = $dbh->prepare("select lastname, firstname,grade from studentall where studnum = ?");

    my $sth1 = $dbh->prepare("select id, tdate, dratype, bktype from read_test 
			     where studnum = ? and readlevel = ? and 
			     to_days( tdate ) >= to_days( '$startdate' ) and
			     to_days( tdate ) <= to_days( '$enddate') 
			     order by tdate $sortorder"); # get tests
    
    my $sth2 = $dbh->prepare("select category, name, score from read_test_score 
			     where testid = ? and seq = ?");

    # Those DRA 2 Reading levels that are nonfiction booktypes; otherwise fiction
    my %nonfiction = ( '16N' => 1, '28N' => 1, '38N' => 1 );

    # Sort by name within table
    my (%sort, @sort);
    foreach my $studnum ( @students ) {
	$sth->execute( $studnum );
	my ( $lastname, $firstname,$grade ) = $sth->fetchrow;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	$sort{"$lastname$firstname$studnum"} = $studnum;
    }
    @sort = sort keys %sort;


    foreach my $key ( @sort ) {
	my $studnum = $sort{$key};

        # Get Name
	$sth->execute( $studnum );
	my ( $lastname, $firstname, $grade ) = $sth->fetchrow;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	# Get Tests
	$sth1->execute( $studnum, $readinglevel );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $trows = $sth1->rows;

	# if $onlylatest, limit to 1 test
	if ( $onlylatest and $trows > 1 ) { $trows = 1; } 

	for ( 1 .. $trows ) {

	    my ( $testid, $tdate, $dratype, $testbktype ) = $sth1->fetchrow;
	    if ( $testbktype ne $bktype and $testbktype ) { next; } # skip if not same fiction/nonfic 

	    print qq{<tr><td class="la"><b>$lastname</b>, $firstname (Gr $grade)</td><td>}.
		fmtDate($tdate). qq{</td>\n};
	    
	    if ( not $testbktype ) {
		if ( $nonfiction{$readlevel} ) {
		    $bktype = 'nonfiction';
		} else {
		    $bktype = 'fiction';
		}
	    }

	    # Loop through all the scores
	    my %studata;
	    my $total = 0;
	    my $count = 0;

	    foreach my $seq ( sort { $a <=> $b } keys %objectives ) { # numeric sort
#		print qq{SEQ:$seq<br>\n};
		$sth2->execute( $testid,$seq );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my ( $category, $name, $score ) = $sth2->fetchrow;

		# Check against objectives
	        my ( $tcat, $tname ) = split(/::/, $objectives{ $seq } );

		if ( not $score ) { # missing
		    if ( $readinglevel == 90 and $g_ReadingEngagementSkip ) {
			next;  # no readingEngagments for this level.
		    }

		    print qq{<div>$firstname $lastname ($studnum) - Test ID:$testid - };
		    print qq{Missing Score for $tcat, $tname SEQ:$seq</div>\n};
		}
		
		
		if ( ($category and $tcat ne $category) or ($name and $tname ne $name) ) { # error if not matching category or
		    print qq{<div>$firstname $lastname ($studnum) - Test ID:$testid - };
		    print qq{$lex{Error} Mismatch: <b>$tcat - $category</b> OR };
		    print qq{<b>$tname - $name</b></div>\n};
		    next;
		}
		$studata{$seq} = $score;
		$total += $score;
		$count++;
	    }

=head
	    # Print the average
	    my $average;
	    if ( $count ) {
		$average = format_number( $total / $count, 2,2 );
	    } else {
		$average = 0;
	    }
=cut
	    print qq{<td>$total</td>\n}; # was $average, from above.
	    
	    # Equivalent Grade
	    my $equivgrade = scoreToGrade( $total, $readinglevel, $dratype );
	    print qq{<td>$equivgrade</td>\n};


	    # Now do the numeric print.
	    my %class = ( 1 => 'r', 2 => 'y', 3 => 'b', 4 => 'g' );
	    foreach my $key ( sort { $a <=> $b } keys %objectives ) { # numeric sort 
		my $val = $studata{$key};
		my $cl = $class{ $val };
		print qq{<td class="$cl">$val</td>};
	    }
	    print qq{</tr>\n};
	} # end of test print loop

    } # end of student loop.

    print qq{</table>\n};
    return;

}

#------------------
sub yearToYearMonth {
#------------------

    use Number::Format qw{round};
    
    my $year = shift;
    if ( not $year ) { return; }

    my ($y,$frac) = split('\.', $year);
    $frac = '0.'. $frac;
    
    my $month = $frac * 12; # get decimal months.
    $month = round($month,0);

    # print "Y:$y Frac:$frac Month:$month<br>\n";

    return $y. q{Y}. $month. q{M};

}



#---------------
sub scoreToGrade {
#---------------

    my ($score, $readinglevel, $dratype ) = @_;  # dratype can be a 2 or a 3.

    if ( not $readinglevel ) { return; }

    
    my %rd_LevelToGrade = ( '0' => 0.1, 1 => 0.3, 2 => 0.6, 3 => 1.0, 4 => 1.2,
			    6 => 1.3, 8 => 1.4, 10 => 1.5, 12 => 1.6, 14 => 1.7,
			    16 => 1.9, 18 => '2.0', 20 => 2.3, 24 => 2.6, 28 => 2.9,
			    30 => 3.3, 34 => 3.6, 38 => 3.9);


    my %rd_ScoreToGrade = (
	50 => 1.9, 51 => 1.9, 52 => 1.9, 53 => 1.9, 54 => '2.0',
	55 => 2.1, 56 => 2.2, 57 => 2.3, 58 => 2.4,
	59 => 2.5, 60 => 2.6, 
	61 => 2.7, 62 => 2.8, 63 => 2.9, 64 => '3.0', 
	65 => 3.1, 66 => 3.2, 67 => 3.3, 68 => 3.4,
	69 => 3.5, 70 => 3.6, 71 => 3.7, 72 => 3.8, 73 => 3.9, 
	74 => '4.0', 75 => 4.1, 76 => 4.2, 77 => 4.3, 78 => 4.4, 79 => 4.5,
	80 => 4.6, 81 => 4.7, 82 => 4.8, 83 => 4.9, 84 => '5.0', 85 => 5.1, 86 => 5.6, 
	87 => 5.3, 88 => 5.4, 89 => 5.5, 90 => 5.6, 91 => 5.7, 92 => 5.8, 93 => 5.9, 
	94 => '6.0', 95 => 6.1, 96 => 6.2, 97 => 6.3, 98 => 6.4, 99 => 6.5, '100' => '6.6',
	101 => 6.6, 102 => 6.8, 103 => 6.9, 
	104 => '7.0', 105 => 7.1, 106 => 7.2, 107 => 7.3, 108 => 7.4, 109 => 7.5, '110' => '7.6',
	111 => 7.7, 112 => 7.8, 113 => 7.9, 114 => '8.0', 115 => 8.1, 116 => 8.2, 117 => 8.3,
	118 => 8.4, 119 => 8.5, 120 => 8.6, 121 => 8.7, 122 => 8.8, 123 => 8.9, 124 => 8.9,
	125 => 8.9, 126 => 8.9,	127 => 8.9, 128 => 8.9 );


    if ( $readinglevel eq '40K' ) { return '4.0'; }

    
    if ( $readinglevel < 40 ) {

	foreach my $key ( sort { $b <=> $a } keys %rd_LevelToGrade ) {
	    if ( $readinglevel >= $key ) {
		return $rd_LevelToGrade{ $key };
	    }
	}

    } else { # else reading level >= 40

	$score += $readinglevel; # add both together

	foreach my $key ( sort { $b <=> $a } keys %rd_ScoreToGrade ) {
	    my $value = $rd_ScoreToGrade{$key};
	    if ( $dratype == 3 ) {   # was $g_DRA3 ) { # DRA 3 mode
		$key -= 8; # subtract 8 from the score key
	    }
	    
	    # print qq{K:$key VAL:$value};
	    if ( $score >= $key ) {
		# print qq{<b>Match: S:$score K:$key V:$rd_ScoreToGrade{$key}</b><br>\n};
		return $value; # was $rd_ScoreToGrade{ $key };
	    }
	}

    }

    return 'NA';
}


# Don't erase this!
1;
