#!/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
);

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_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
);
use Textbook::Course qw(
    course_findById
);

use Textbook::Distribution qw(
   getDistributions2ReceiverByType  
);
use Textbook::SchoolYear qw(
    schoolyear_getCurrent
);

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/collSearchResult.tmpl',
            reqPermission   => 'report', #textbook
        }
);

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

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


my $schoolYearId;
my $schoolYear=schoolyear_getCurrent($dbh);
if ($schoolYear){
    $schoolYearId=$schoolYear->{'id'};
}

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


   if($collectionType eq "teachers" || $collectionType eq "students"){
        $tmpRs = getDistributions2ReceiverByType($dbh,{receiverType     => $collectionType,
                                                       receiverId       => $selVal,
                                                       schoolYearId     => $schoolYearId});
        foreach my $d( @{$tmpRs}){
            my $td= distributedConversion($d);
            $td->{'prepOrder'} =$prepOrder++;
            $td->{'pid'} =  $d->{'pid'};
            push   @resultList,  $td;  
        }
        
        my $numOfDist = scalar(@resultList);
        if($numOfDist>0){
            $template->param(numOfDist    => $numOfDist); 
        }
        if($collectionType eq "teachers"){
            my $teacherInfo = teacher_findById($dbh,$selVal);
            $template->param( teachers      => 1,
                              teacherId     => $teacherInfo->{'teacherId'},
                              firstName     => $teacherInfo->{'firstName'},
                              lastName      => $teacherInfo->{'lastName'} );
        }
        else{
            my $studentInfo = student_findById($dbh,$selVal);
            $template->param( students      => 1,
                              studentId     => $studentInfo->{'studentId'},
                              firstName     => $studentInfo->{'firstName'},
                              lastName      => $studentInfo->{'lastName'} );
        }

        $template->param( distributions => \@resultList,
                          todayStr      => date_text($todayStr) );

    }# if($collectionType eq "teachers" OR "students")

    elsif($collectionType eq "courses"){
    }
    elsif($collectionType eq "homeroom"){
    }
   

    $template->param( collectionType => $collectionType);
                          
    
################################################################################
sub distributedConversion{
    my ($distribution)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,0);
    my($curCourseId,$curSectionId)=("","");
    my $className="";
    my $nCollections=0;  
    foreach my $d(@{$distribution->{'bookDist'}}){
        if($curCourseId ne $d->{'courseId'}){
            $curCourseId=$d->{'courseId'};
            $i++;
            $j=-1;
            my $course=course_findById($dbh,$d->{'courseId'});
            push @courseList,{
                              courseId   =>$d->{'courseId'},
                              courseName =>$course->{'courseName'},
                              courseCode =>$course->{'courseCode'},
                              nSections=>0,
                              nISBNs=>0,
                              c_order=>$i
                             };
        }
        if($curSectionId ne $d->{'sectionId'}){
            $curSectionId = $d->{'sectionId'};
            @courseList[$i]->{'nSections'} +=1;
            $j++;    
            $k=0;        
            push @{@courseList[$i]->{'sectionList'}},{sectionId=>$d->{'sectionId'},nISBNs=>0,s_order=>$j};
        }
        my $s = @{@courseList[$i]->{'sectionList'}}[$j];
        my $book = book_getByIsbn($dbh,$d->{'ISBN'});
        $nCollections = $d->{'ok'} + $d->{'damaged'}  + $d->{'lost'} ;
        my $isDone =0;
        if(int($nCollections) == int($d->{'distributed'})){
             $isDone = 1;
        }

        push @{$s->{'bookList'}}, {ISBN          => $d->{'ISBN'},
                                   title         => $book->{'title'},
                                   distributed   => $d->{'distributed'},
                                   nCollections  => $nCollections,
                                   ok            => $d->{'ok'},
                                   damaged       => $d->{'damaged'},
                                   lost          => $d->{'lost'},
                                   isDone        => $isDone,
                                   isbn_order=>$k++
                                   };
                
        $s->{'nISBNs'} +=1;
        @courseList[$i]->{'nISBNs'} +=1;

    }
    $retval={courseList=>\@courseList, };
    return  $retval;

}

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

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

