#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use POSIX qw(
    ceil
);

use Opals::Context;
use Date::Calc::Object qw(
    :all
);
use POSIX qw(
    floor
);
use Time::localtime;

use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_validateWorkday
    date_deltaWorkDay
    date_addDeltaWorkday
);

use Opals::User qw(
    user_getInformation
);
use Opals::MarcXml qw(
    mxml_delete
);
use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_f005
);
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);


use Textbook::Search qw(
    search_user
    search_student
    search_teacher
    search_course
    search_homeroom
);

use Textbook::Books qw(
    bookList_forCourse
    bookList_forTeacher
    bookList_forStudent
    bookList_forHomeroom
    book_TotalAvailable

    book_getByIsbn
);
use Textbook::Students qw(
    student_getListByCourse
    student_findById

);
use Textbook::Teachers qw(
    teacher_findById
    teacher_findByCourseSectionId
);

use Textbook::Preparation qw(
    getPreparation_teacher
    getPreparation_student
    getPreparation_course
    getPreparation_homeroom
);
use Textbook::Course qw(
    course_findById
);
use Textbook::Distribution qw(
  countBookDistByISBN
);


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'textbook/distSearchResult.tmpl',
            reqPermission   => 'report', #textbook
        }
);

my $tm = localtime;
my $todayStr = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);

my $distributionType = $input->{'preparationType'};
my $selVal           = $input->{'selVal'};



my $schoolYearId=1;
my ($param,$noISBNPerCourse,$noCoursePerPrep);
my (@resultList,$tmpRs);
my ($curCourseId,$curSectionId,$pid); 


  $template->param(list => 1);

   if($distributionType eq "teachers"){
        my $teacherInfo = teacher_findById($dbh,$selVal);
        $tmpRs =getPreparation_teacher($dbh,{teacherId         => $selVal,
                                             schoolYearId      => $schoolYearId,
                                             recipient         => 'teacher',
                                             expectedReadiness => $todayStr });
        my $prepOrder=0;
        foreach my $p( @{$tmpRs}){
            my $tp= teacherPrepConversion($p);
            $tp->{'prepOrder'} =$prepOrder++;
            push   @resultList,  $tp;        
        }
        my $numOfPrep = scalar(@resultList);
        
        
        if($numOfPrep>0){
            $template->param(numOfPrep    => $numOfPrep); 
        }
        $template->param( preparations => \@resultList,
                          teachers     => 1,
                          teacherId    => $teacherInfo->{'teacherId'},
                          firstName    => $teacherInfo->{'firstName'},
                          lastName     => $teacherInfo->{'lastName'},
                          todayStr     => $todayStr );

    }# if($distributionType eq "teachers")

    elsif($distributionType eq "students"){        
        my $studentInfo = student_findById($dbh,$selVal);
              
        $tmpRs =getPreparation_student($dbh,{studentId        => $selVal,
                                            schoolYearId      => $schoolYearId,
                                            recipient         => 'student',
                                            expectedReadiness => $todayStr });
        my $prepOrder=0;

        foreach my $p( @{$tmpRs}){
            my $tp= studentPrepConversion($p,$selVal);
            $tp->{'prepOrder'} =$prepOrder++;
            push   @resultList,  $tp; 
        }

        my $numOfPrep = scalar(@resultList);
        if($numOfPrep>0){
            $template->param(numOfPrep    =>  $numOfPrep); 
        }
        
        $template->param(
                  preparations => \@resultList, 
                  students     => 1,
                  studentId    => $studentInfo->{'studentId'},
                  firstName    => $studentInfo->{'firstName'},
                  lastName     => $studentInfo->{'lastName'},
                  todayStr     => $todayStr );

    }# if ($distributionType eq "students")

    elsif($distributionType eq "courses"){
        my $courseInfo = course_findById($dbh, $selVal);
        $tmpRs = getPreparation_course($dbh,$selVal ,$schoolYearId);

        my $prepOrder=0;
        foreach my $p (@{$tmpRs}){
            my $tp = coursePrepConversion($p);
            $tp->{'prepOrder'} = $prepOrder++;
            push @resultList, $tp;
        }
      
      my $numOfPrep = scalar(@resultList);
        
        if($numOfPrep>0){
            $template->param(numOfPrep    =>  $numOfPrep); 
        }

        $template->param(
                    preparations    =>\@resultList,
                    courses         =>1,
                    courseId        =>$selVal,
                    courseCode      =>$courseInfo->{'courseCode'},
                    courseName      =>$courseInfo->{'courseName'},
                    todayStr        =>$todayStr
        
        );
    }# if$distributionType eq "courses")

    elsif($distributionType eq "homeroom"){

        $tmpRs = getPreparation_homeroom($dbh, $selVal, $schoolYearId);
        my $prepOrder=0;
       
        foreach my $p (@{$tmpRs}){
            my $tp = homeroomPrepConversion($p);
            $tp->{'prepOrder'} = $prepOrder++;
            push @resultList, $tp;
        }
        $template->param(
                preparations    =>\@resultList,
                homerooms       =>1,
                homeroom        =>$selVal,
                todayStr        =>$todayStr,
        );
    }#if distrubtionType eq "homeroom"

    elsif($distributionType eq "quick"){
        my $userType;
        my $userInfo;
        
        $param={userId=>$selVal};
        my $rs = search_user($dbh,$param);
        $userInfo =  @{$rs->{'userList'}}[0]; 
        
        $template->param(
                    userId          => $selVal,
                    firstName       => $userInfo->{'firstName'},
                    lastName        => $userInfo->{'lastName'},
                    quick           => 1,
                    todayStr        => $todayStr,
        
       );

    }
   

    $template->param(distributionType => $distributionType);
                          
################################################################################
sub studentPrepConversion{
    my ($prep,$studentId)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,0);
    my($curCourseId,$curSectionId)=("","");
    my $className="";
    my $curIsbn;
    foreach $b(@{$prep->{'book2Prepare'}}){
        
         if($curCourseId ne $b->{'courseId'}){
            $curCourseId=$b->{'courseId'};
            $i++;
            $j=-1;
            $k=0;
            my $course=course_findById($dbh,$b->{'courseId'});

            if(!$b->{'teacherId'}){
                my $t = search_teacher($dbh,{courseCode=>$course->{'courseCode'},
                                               sectionId=>$b->{'sectionId'} });
                my $stdList=$t->{'teacherList'};
                foreach my $tInfo(@$stdList){
                    $b->{'teacherId'} = $tInfo->{'teacherId'};
                }
            }

            my $teacherInfo = teacher_findById($dbh,$b->{'teacherId'});

            push @courseList,{courseId      => $b->{'courseId'},
                              courseName    => $course->{'courseName'},
                              courseCode    => $course->{'courseCode'},
                              teacherId     => $teacherInfo->{'teacherId'},
                              t_firstName   => $teacherInfo->{'firstName'},
                              t_lastName    => $teacherInfo->{'lastName'},
                              sectionId     => $b->{'sectionId'},
                              nISBNs        =>0,
                              c_order       => $i,
                             };
            }
            my $book = book_getByIsbn($dbh,$b->{'ISBN'}); 
            $className = "";
            my $params ={receiverType=>'students', receiverId=>$studentId,
                         schoolYearId=>$schoolYearId, courseId=>$b->{'courseId'},
                         sectionId=>$b->{'sectionId'},ISBN=>$b->{'ISBN'}};
            my ($nBookDist,$nBookReq) ;

            if($prep->{'type'} eq 'teacher') {            
                my $bookCount = countBookDistByISBN($dbh,$params);
                foreach my $n(@$bookCount){
                    $nBookDist =   $n->{'bCount'};
                }
                $nBookReq = $b->{'nCopiesPerAllocation'};

            }
            elsif($prep->{'type'} eq 'student') {
                $nBookDist = $b->{'nDistributed'};
                $nBookReq  = $b->{'total'};
            }
            if ($nBookReq eq $nBookDist){
                $className="distDone";
            }
            if ($curIsbn ne $b->{'ISBN'}){
                $curIsbn = $b->{'ISBN'};
                       push @{@courseList[$i]->{'bookList'}}, 
                            {ISBN          => $b->{'ISBN'},
                            title          => $book->{'title'},
                            nDistributed   => $nBookDist,
                            allocationType => $b->{'allocationType'},
                            nCopies        => $b->{'nCopiesPerAllocation'},
                            total          => $nBookReq,
                            wDistribute    => $nBookReq - $nBookDist,
                            className      => $className,
                            isbn_order     => $k++
        };
        }
        if ($className eq 'distDone'){
            @courseList[$i]->{'distDone'}=1;
        }
     }
    $retval={pid=>$prep->{'pid'},
             type=>uc($prep->{'type'}),
             preparedDate=>$prep->{'preparedDate'},
             expectedReadiness=>$prep->{'expectedReadiness'},
             courseList=>\@courseList,
             };
    return  $retval;  
}

################################################################################
sub teacherPrepConversion{
    my ($prep)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,0);
    my($curCourseId,$curSectionId)=("","");
    my $className="";
    foreach $b(@{$prep->{'book2Prepare'}}){
         if($curCourseId ne $b->{'courseId'}){
            $curCourseId=$b->{'courseId'};
            $i++;

            $j=-1;
            my $course=course_findById($dbh,$b->{'courseId'});
            push @courseList,{courseId   =>$b->{'courseId'},
                              courseName =>$course->{'courseName'},
                              courseCode =>$course->{'courseCode'},
                              nSections=>0,
                              nISBNs=>0,
                              c_order=>$i
                             };

        }
        if($curSectionId ne $b->{'sectionId'}){
            $curSectionId = $b->{'sectionId'};
            @courseList[$i]->{'nSections'} +=1;
            $j++;    
            $k=0;        
            push @{@courseList[$i]->{'sectionList'}},{sectionId=>$b->{'sectionId'},nISBNs=>0,s_order=>$j};
        }
        my $s = @{@courseList[$i]->{'sectionList'}}[$j];
        my $book = book_getByIsbn($dbh,$b->{'ISBN'}); 
        $className="";
        if($b->{'nDistributed'} eq $b->{'total'}){
            $className="distDone";
        }

        push @{$s->{'bookList'}}, {ISBN          => $b->{'ISBN'},
                                   title         => $book->{'title'},
                                   nDistributed  => $b->{'nDistributed'},
                                   total         => $b->{'total'},
                                   wDistribute   => $b->{'total'} - $b->{'nDistributed'},
                                   className     => $className,
                                   isbn_order=>$k++
                                   };
        $s->{'nISBNs'} +=1;  
        if($className eq "distDone"){
            $s->{'distDone'} =1;
            $s->{'className'} =$className;
            @courseList[$i]->{'distDone'} =1;

        }
        @courseList[$i]->{'nISBNs'} +=1;
    }
    $retval={pid=>$prep->{'pid'},type=>$prep->{'type'},
             preparedDate=>$prep->{'preparedDate'},
             expectedReadiness=>$prep->{'expectedReadiness'},
             courseList=>\@courseList,
             };
   return  $retval;
}


sub coursePrepConversion{

 my ($prep)=@_;
    my $retval;
    my @sectionList;
    my($i,$j,$k)=(-1,-1,0);
    my $curSectionId="";
    my $className=""; 
    my $distDone = 0;
    my @bookList;
    my $nISBN=0;

    foreach $b(@{$prep->{'book2Prepare'}}) {

        $nISBN++;

        if($curSectionId ne $b->{'sectionId'}){
            $curSectionId = $b->{'sectionId'};
            $i++;
             
            push @sectionList, {sectionId   => $b->{'sectionId'},
                                nStudents   => $b->{'nStudents'},
                                nISBNs      => 0,
                                s_order     => $i,
                            };
           $k=0;
          }
        if($b->{'nDistributed'} eq $b->{'total'}){
            $className="distDone";
            @sectionList[$i]->{'distDone'} =1;
            $distDone = 1;

        }

        @sectionList[$i]->{'nISBNs'} +=1;
        my $book = book_getByIsbn($dbh,$b->{'ISBN'});
        push @{@sectionList[$i]->{'bookList'}}, {  
                        ISBN            =>$b->{'ISBN'},
                        title           =>$book->{'title'},
                        total           =>$b->{'total'},
                        allocationType  =>$b->{'allocationType'},
                        nDistributed    =>$b->{'nDistributed'},
                        wDistribute     =>$b->{'total'} - $b->{'nDistributed'},
                        recipient       =>  $b->{'recipient'},
                        isbn_order      =>  $k++,
                        className       =>  $className,
                        

            };
    }
                                 
    $retval={   
                pid             =>$prep->{'pid'},
                type            =>$prep->{'type'},
                prepareDate     =>$prep->{'preparedDate'},
                expectedReadiness=>$prep->{'expectedReadiness'},
                distDone        =>$distDone,
                sectionList     =>\@sectionList,
                className       =>$className,

                };


    return $retval;
    }

sub homeroomPrepConversion{

    my ($prep)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,0);
    my($curCourseId,$curSectionId)=("","");
    my $className="";
    foreach $b(@{$prep->{'book2Prepare'}}){
         if($curCourseId ne $b->{'courseId'}){
            $curCourseId=$b->{'courseId'};
            $i++;
            $j=-1;
            my $course=course_findById($dbh,$b->{'courseId'});
            push @courseList,{courseId   =>$b->{'courseId'},
                              courseName =>$course->{'courseName'},
                              courseCode =>$course->{'courseCode'},
                              nSections=>0,
                              nISBNs=>0,
                              c_order=>$i
                             };

        }
        if($curSectionId ne $b->{'sectionId'}){
            $curSectionId = $b->{'sectionId'};
            @courseList[$i]->{'nSections'} +=1;
            $j++;    
            $k=0;        
            push @{@courseList[$i]->{'sectionList'}},
                {sectionId=>$b->{'sectionId'},
                nISBNs=>0, 
                nStudents=>$b->{'nStudents'},
                s_order=>$j,
                };
        }
        my $s = @{@courseList[$i]->{'sectionList'}}[$j];
        my $book = book_getByIsbn($dbh,$b->{'ISBN'}); 
        $className="";
        if($b->{'nDistributed'} eq $b->{'total'}){
            $className="distDone";
        }

        push @{$s->{'bookList'}}, {ISBN         => $b->{'ISBN'},
                                   title        => $book->{'title'},
                                   nDistributed => $b->{'nDistributed'},
                                   total        => $b->{'total'},
                                   wDistribute  => $b->{'total'} - $b->{'nDistributed'},
                                   className    => $className,
                                   recipient    => $b->{'recipient'},
                                   isbn_order   => $k++,
                                   };
        $s->{'nISBNs'} +=1;  
        if($className eq "distDone"){
            $s->{'distDone'} =1;
            $s->{'className'} =$className;
            @courseList[$i]->{'distDone'} =1;

        }
        @courseList[$i]->{'nISBNs'} +=1;
    }
    $retval={pid=>$prep->{'pid'},type=>$prep->{'type'},
             preparedDate=>$prep->{'preparedDate'},
             expectedReadiness=>$prep->{'expectedReadiness'},
             courseList=>\@courseList,
             };
   return  $retval;


}
   
################################################################################
    
tmpl_write($dbh, $cgi, $cookie, $template);
#$dbh->disconnect();

################################################################################

