#!/usr/bin/perl 
use lib "/www/opals/module";
use Opals::Context("/etc/opals/conf/ztest");

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

    search_prep_student
    search_prep_teacher
    search_prep_course
    search_prep_homeroom
);
use Textbook::Books qw(
    bookList_forCourse
    bookList_forTeacher
    bookList_forStudent
    bookList_forHomeroom
    book_TotalAvailable
);
use Textbook::Students qw(
    student_getListByCourse
    student_getListByHomeroom
    student_getListByTeacher
    student_add
    student_update
    student_delete
    student_find
    student_findById
);


use Textbook::Teachers qw(
    teacher_getListByCourse

    teacher_add
    teacher_update
    teacher_delete
    teacher_find
    teacher_findById
);
use Textbook::SchoolYear qw(
    schoolyear_getCurrent
    schoolyear_add
    schoolyear_delete
    schoolyear_update
    schoolyear_list
);
use Textbook::Preparation qw(
    prepare_student
    prepare_teacher
    prepare_course
    prepare_homeroom
    getPreparation_byId
    getPreparation_teacher
    getPreparation_student

);

use Textbook::Course qw(
    course_findById
);

use Textbook::Collection qw(
    collectFromTeacher_woBc
);

use Textbook::Distribution qw(
   getDistributions2ReceiverByType

);
#----------------------------------------------------
=item
my $p={a=>1};
my @a=({x=>'a1',y=>2,z=>3},{x=>'a1',y=>5,z=>6},{x=>'a2',y=>2,z=>3},);
my $p;
my $i=0;
foreach my $t(@a){
    if(!$p->{'x'}){
        $p->{'x'}->{'x1'}=$t->{'x'};
        $i=0;
    }
    $i++;
    push @{$p->{'x'}->{'aaa'}},{z=>$i};
}
foreach my $t(keys %{$p}){
    my $r =$p->{$t};
    print "=$t======", $p->{$t}->{'x1'}," ======\n";

    foreach my $k( @{$r->{'aaa'}}){
        
        print $k->{'z'} . "\n";
    }
}

=cut

my $dbh = Opals::Context->dbh();
 
#testCollectionFromTeacherWoBc();
#testgetDistribution2Teacher();
#testSearchUser();
#testSearchStudent();
#testSearchTeacher();
#testSearchCourse();
#testBooklistForTeacher();
#testSearchHomeroom();
#testBooklistForCourse();
#testBookTotalAvailable();
#testBooklistForStudent();
#testStudentListBycourse();
#testStudentListByTeacher();
#testStudentListByHomeroom();
#print testStudentAddNew(), "\n";
#print testStudentUpdate(), "\n";
#testStudentFind();

#testTeacherAddNew();
#testTeacherFind();
#testTeacherFindById();
#testStudentFindById();
#testTeacherDelete();
#testTeacherListByCourse();
#testSchoolYear_add();
#testSchoolYear_update();
#testSchoolYear_getCurrent();

#testPreparationStudent();
#testPreparationTeacher();
#testPreparationCourse();
#testpreparationGetTeacher();
#testpreparationGetStudent();
#testpreparationGetById();

#testSearch_prep_Teacher();
#testSearch_prep_student();
#testSearch_prep_course();
#testSearch_prep_homeroom();


sub testCollectionFromTeacherWoBc{

    collectFromTeacher_woBc($dbh,{pid=>13,ISBN=>'0028251792',
                                    courseId=>91,
                                    sectionId=>'1',
                                    teacherId=>'1004356',
                                    nCopies_ok=>1,
                                    nCopies_damaged=>2,
                                    nCopies_lost=>0,
                                    schoolYearId=>1}                                   
                                    
    
    );

}
sub testpreparationGetStudent{
    my $p =getPreparation_student($dbh,'1111',1);
    foreach my $pid(keys %{$p}){
        print "Preparation Id: $pid \t Type: " ,$p->{$pid}->{'type'}, "\n";
        my $bookList = $p->{$pid}->{'book2Prepare'};

        print"\tISBN     \t NumberOfStudent  \t AlocationType \t CopiesPerAllocation \t total\ \t Distributed\n";
        
        foreach my $b(@$bookList){
#$bookList : array of all information from table tbk_preparationDetails; field names are identical as well.
            print "\t" , $b->{'ISBN'} , "     \t\t   " , 
            $b->{'nStudents'} ,"\t\t " , 
            $b->{'allocationType'} ,"\t\t ", 
            $b->{'nCopiesPerAllocation'},"\t\t  ", 
            $b->{'total'} ,"\t\t", 
            $b->{'nDistributed'} , "\n";
        }
    }
}
sub testpreparationGetById{
    my $p =getPreparation_byId($dbh,'13',1);

        my $tmp;
        my $bList=$p->{'book2Prepare'};

        foreach my $b(@$bList){
           if (!$tmp->{$b->{'courseId'}}){
               my $course=course_findById($dbh,$b->{'courseId'});
               $tmp->{$b->{'courseId'}}=$course;
           }
           if (!$tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}){
               $tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}->{'nStudents'}=$b->{'nStudents'};
           }
           push @{$tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}->{'books'}},
                {ISBN=>$b->{'ISBN'},allocationType=>$b->{'allocationType'},
                nCopiesPerAllocation=>$b->{'nCopiesPerAllocation'},total=>$b->{'total'}};
          
            print "ha:" , $b->{'courseId'}, "\n";
        }
my $i=0;
my @courseList;
foreach my $k(keys %{$tmp}){
    push @courseList,{courseId=>$k,
                      courseCode=>$tmp->{$k}->{'courseCode'},
                      courseName=>$tmp->{$k}->{'courseName'}
                      };

                       
    foreach my $s(keys %{$tmp->{$k}->{'sections'}}){
        push @{$courseList[$i]->{'sections'}},$tmp->{$k}->{'sections'}->{$s};
        
          }
    $i++;

}

foreach my $c(@courseList){
    print $c->{'courseId'} , "--", $c->{'courseCode'} ,$c->{'courseName'} ,"\n";
    foreach my $ss (@{$c->{'sections'}}){
        print "\t", $ss->{'sectionId'} , "--", $ss->{'nStudents'} , "\n";
        foreach my $bb(@{$ss->{'books'}}){
           print "\t\t", $bb->{'ISBN'} , "--", $bb->{'total'} , "\n";

        }
    }

}
        print "Preparation Id: $pid \t Type: " ,$p->{'type'}, "\n";
        my $bookList = $p->{'book2Prepare'};

        print"\tISBN  \t\tcourseId   \tsection \tNumberOfStudent  \t AlocationType \t CopiesPerAllocation \t total  \tnDistributed \n";
        
        foreach my $b(@$bookList){
#$bookList : array of all information from table tbk_preparationDetails; field names are identical as well.
            print "\t" , $b->{'ISBN'} , "     \t   " , 
            $b->{'courseId'},"\t\t",
            $b->{'sectionId'},"\t\t",
            $b->{'nStudents'} ,"--\t\t\t " , 
            $b->{'allocationType'} ,"\t\t ", 
            $b->{'nCopiesPerAllocation'},"\t\t  ", 
            $b->{'total'} ,"\t\t", 
            $b->{'nDistributed'} , "\n";
        }
    
}
sub testpreparationGetTeacher{
    my $preps =getPreparation_teacher($dbh,{teacherId=>'1004356',schoolYearId=>1,recipient=>'teacher--'});
    foreach my $p( @{$preps}){

       my $tp= teacherPrepConversion($p);
       print $tp->{'pid'} , "\n";
       foreach my $c(@{$tp->{'courseList'}}){
           print "\t",$c->{'courseId'} ,"\n";
           foreach my $s(@{$c->{'sectionList'}}){
               print "\t\t " , $s->{'sectionId'} ,"\n";
               foreach my $b(@{$s->{'bookList'}}){
                   print  "\t\t \t" , $b->{'ISBN'} ,"\n";

               }
           }
       }


  
=item  
        print "Preparation Id: ", $p->{'pid'} ,"\t Type: " ,$p->{'type'}, "\n";
        print "Preparation Date: ", $p->{'preparedDate'} ,"\t Distribution Date: " ,$p->{'expectedReadiness'}, "\n";
        my $bookList = $p->{'book2Prepare'};

        print"\tISBN     \t NumberOfStudent  \t AlocationType \t CopiesPerAllocation \t total \t recipient \t distributed\n";
        
        foreach my $b(@$bookList){
#$bookList : array of all information from table tbk_preparationDetails; field names are identical as well.
            print "\t" , $b->{'ISBN'} , "     \t\t   " , 
            $b->{'nStudents'} ,"\t\t " , 
            $b->{'allocationType'} ,"\t\t ", 
            $b->{'nCopiesPerAllocation'},"\t\t  ", 
            $b->{'total'} ,"\t", 
            $b->{'recipient'} ,"\t\t", 
            $b->{'nDistributed'} , "\n";
        }
=cut        
    }
}
sub teacherPrepConversion{
    my ($prep)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,-1);
    my($curCourseId,$curSectionId)=("","");
    foreach $b(@{$prep->{'book2Prepare'}}){
        if($curCourseId ne $b->{'courseId'}){
            $curCourseId=$b->{'courseId'};
            $i++;
            $j=-1;
            push @courseList,{courseId=>$b->{'courseId'}};
        }
        if($curSectionId ne $b->{'sectionId'}){
            $curSectionId = $b->{'sectionId'};
            $j++;
            push @{@courseList[$i]->{'sectionList'}},{sectionId=>$b->{'sectionId'}};

        }
        my $s = @{@courseList[$i]->{'sectionList'}}[$j];
        push @{$s->{'bookList'}}, {ISBN=>$b->{'ISBN'},total=>$b->{'total'}};
    }
    $retval={pid=>$prep->{'pid'},type=>$prep->{'type'},
             preparedDate=>$prep->{'preparedDate'},
             expectedReadiness=>$prep->{'expectedReadiness'},
             courseList=>\@courseList};
    return  $retval;

}
sub testPreparationStudent{
    my $params={preparedBy=>1,schoolYearId=>1,expectedReadiness=>'2008-09-01'};
    my @book2Prepare=();
    push  @book2Prepare,{studentId=>'1111',courseId=>'2',sectionId=>1,nCopies=>2,ISBN=>'123456'};
    push  @book2Prepare,{studentId=>'1111',courseId=>'2',sectionId=>1,nCopies=>2,ISBN=>'123457'};
    push  @book2Prepare,{studentId=>'1111',courseId=>'3',sectionId=>1,nCopies=>2,ISBN=>'123458'};
    $params->{'book2Prepare'}=\@book2Prepare;
    print prepare_student($dbh,$params) ,"\n";
}
sub testPreparationTeacher{
    my $params={preparedBy=>1,schoolYearId=>1,expectedReadiness=>'2008-09-01'};
    my @book2Prepare=();
    push  @book2Prepare,{teacherId=>'222',courseId=>'2',sectionId=>1,nStudents=>12,nCopiesPerAllocation=>2,ISBN=>'123456',allocationType=>'perStudent',recipient=>'teacher'};
    push  @book2Prepare,{teacherId=>'222',courseId=>'2',sectionId=>1,nStudents=>10,nCopiesPerAllocation=>1,ISBN=>'123457',allocationType=>'perStudent',recipient=>'teacher'};
    push  @book2Prepare,{teacherId=>'222',courseId=>'3',sectionId=>1,nStudents=>10,nCopiesPerAllocation=>1,ISBN=>'123458',allocationType=>'perStudent',recipient=>'teacher'};
    $params->{'book2Prepare'}=\@book2Prepare;
    print prepare_teacher($dbh,$params) ,"\n";
}
sub testPreparationCourse{
    my $params={preparedBy=>1,schoolYearId=>1,expectedReadiness=>'2008-09-01'};
    my @book2Prepare=();
    push  @book2Prepare,{courseId=>'2',sectionId=>1,nStudents=>12,nCopiesPerAllocation=>2,ISBN=>'123456',allocationType=>'perStudent',recipient=>'teacher'};
    push  @book2Prepare,{courseId=>'2',sectionId=>1,nStudents=>10,nCopiesPerAllocation=>1,ISBN=>'123457',allocationType=>'perStudent',recipient=>'teacher'};
    push  @book2Prepare,{courseId=>'3',sectionId=>1,nStudents=>10,nCopiesPerAllocation=>1,ISBN=>'123458',allocationType=>'perStudent',recipient=>'teacher'};
    $params->{'book2Prepare'}=\@book2Prepare;
    print prepare_course($dbh,$params) ,"\n";
}
sub testSchoolYear_update{
    my $params={id=>2, firstDate=>'2008-09-01',lastDate=>'2009-06-60'};
    schoolyear_update($dbh,$params);
}
sub testSchoolYear_add{
    my $params={schoolYear=>'2009-2010'};

    my $y = schoolyear_add($dbh,$params);
    print $y , "\n" ;
}
sub testSchoolYear_getCurrent{
    my $y = schoolyear_getCurrent($dbh);
    print $y->{'id'}, "--", $y->{'schoolYear'} , $y->{'firstDate'},$y->{'lastDate'},"\n" if($y );
}

sub testTeacherListByCourse{
    #my $params={courseCode=>'0475',schoolYear=>'1'};
    my $params={courseCode=>'0475', sectionId=>'5',schoolYear=>'1'};
    $list=teacher_getListByCourse($dbh,$params);
    foreach my $t (@$list){
        print $t->{'lastName'}, ", " , $t->{'firstName'} ,"\n";
    }

}

sub testTeacherDelete{
    $teacherId='12345';
    teacher_delete($dbh,$teacherId);
}


sub testTeacherUpdate{
    my $params={teacherId=>'12345', firstName=>'kkk'};
    $stdList =teacher_update($dbh,$params);
    foreach my $s(@$stdList){
        print $s->{'lastName'} ,"\n";
    }
}

sub testTeacherFind{
    my $params={lastName=>'kkk'};
    $stdList =teacher_find($dbh,$params);
    foreach my $s(@$stdList){
        print $s->{'lastName'} ,"\n";
    }
}
sub testTeacherFindById{
    $teacher =teacher_findById($dbh,'1004356');
    if($teacher) {
        print $teacher->{'lastName'} ,"\n";
    }
}

sub testTeacherAddNew{
    my $params={teacherId=>'12345',lastName=>'kkk'};
    teacher_add($dbh,$params);
}

sub testStudentFind{
    my $params={studentId=>'12345',firstName=>'kkk'};
    $stdList =student_find($dbh,$params);
    foreach my $s(@$stdList){
        print $s->{'lastName'} ,"\n";
    }
}
sub testStudentFindById{
    $student =student_findById($dbh,'412480');
    if($student) {
        print $student->{'lastName'} ,"\n";
    }
}


############################################################
sub testStudentUpdate{
    my $params={studentId=>'12345',firstName=>'kkk'};
    student_update($dbh,$params);
}

############################################################
sub testStudentAddNew{
    my $params={studentId=>'12345',lastName=>'kkk'};
    student_add($dbh,$params);
}

############################################################
sub testStudentListByHomeroom{

    my $homeroom = '123';

    my $list=student_getListByHomeroom($dbh,$homeroom);
        foreach my $s(@$list){
            print "\t", $s->{'lastName'},"\n";
    }

}


############################################################
sub testStudentListByTeacher{

    my $params={teacherId=>'1004356', schoolYear=>'1'};
    #my $params={teacherId=>'1004356', courseCode=>'0330',schoolYear=>'1'};
    #my $params={teacherId=>'1004356', courseCode=>'0330',sectionId=>'4',schoolYear=>'1'};

    $list=student_getListByTeacher($dbh,$params);
    my $sss = $list->{'0'};
    print scalar @$sss ,"\n";
    foreach my $section(keys %$list){
        print $section,"\n";
        my $a =$list->{$section};
        print  scalar( @$a);
        foreach my $s(@$a){
            print "\t", $s->{'lastName'},"\n";
        }
    }

}

############################################################
sub testStudentListBycourse{
    my $params={courseCode=>'0475', sectionId=>'5',schoolYear=>'1'};
    $list=student_getListByCourse($dbh,$params);
    my $sss = $list->{'0'};
    print scalar @$sss ,"\n";
    foreach my $section(keys %$list){
        print $section,"\n";
        my $a =$list->{$section};
        print  scalar( @$a);
        foreach my $s(@$a){
            print "\t", $s->{'lastName'},"\n";
        }
    }

}

############################################################
sub testBookTotalAvailable{
    print book_TotalAvailable($dbh,'0021103542'), "\n";
}
############################################################
sub testBooklistForCourse{
     my $param={courseCode=>'0111'};

    my @stdList=bookList_forCourse($dbh,$param);
    for( my $i=0; $i < 10 && $i <scalar(@stdList)  ; $i++){
        print @stdList[$i]->{"isbn"} , ", " , @stdList[$i]->{"title"} ,"\n";
        my $sections=@stdList[$i]->{"section"};
            print @$sections[0]->{'sectionId'} ."\n";
    }

}

############################################################
sub testBooklistForTeacher{
     my $param={teacherId=>'1004150'};

    my @stdList=bookList_forTeacher($dbh,'1004150');
    for( my $i=0; $i < 10 && $i <scalar(@stdList)  ; $i++){
        print @stdList[$i]->{"isbn"} , ", " , @stdList[$i]->{"title"} ,"\n";
        my $sections=@stdList[$i]->{"section"};
        
    }

}
############################################################
sub testBooklistForStudent{
     my $param={studentId=>'1004150'};

    my @stdList=bookList_forStudent($dbh,'001923');
    for( my $i=0; $i < 10 && $i <scalar(@stdList)  ; $i++){
        print @stdList[$i]->{"isbn"} , ", " , @stdList[$i]->{"title"} ,"\n";
        my $sections=@stdList[$i]->{"section"};
        
    }

}

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

sub testSearchStudent{
    #my $param={offset=>'0',count=>'5'};
    my $param={name=>'joe smith '};
    my $name='smith ';
    $name =~ s/ $//g;
    print "[$name]\n";
    my $result = search_student($dbh,$param);
    my $stdList=$result->{'userList'};
    print "$found\n";
    for( my $i=0; $i < 10 && $i <scalar(@$stdList)  ; $i++){
        print @$stdList[$i]->{"studentId"} , ", " , @$stdList[$i]->{"firstName"} ,", " ,@$stdList[$i]->{"lastName"},"\n"
    }


}
############################################################

sub testSearchUser{
    #my $param={offset=>'0',count=>'5'};
    my $param={name=>'McClafferty'};
    my $name='dia';
    $name =~ s/ $//g;
    my $result = search_user($dbh,$param);
    my $userList=$result->{'userList'};
    my $found=$result->{'found'};
    print "$found\n";
    for( my $i=0; $i < 10 && $i <scalar(@$userList)  ; $i++){
        print @$userList[$i]->{"userId"} , ", " , @$userList[$i]->{"firstName"} ,", " ,@$userList[$i]->{"lastName"}, "  " , @$userList[$i]->{"userType"},"\n"
    }

    
}

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

sub testSearch_prep_Teacher{
  # my $param={teacherId=>'1004356', courseCode=>'0330'};
  # my $param={courseCode=>'0480', sectionId=>'17'};
  my $param={};

    my $result = search_prep_teacher($dbh,$param);
     
my $stdList=$result->{'teacherList'};
    foreach my $t (@$stdList){
        print $t->{"teacherId"} , ", " , $t->{"firstName"} ,", " ,$t->{"lastName"},"\n"
    }


}


############################################################
sub testSearch_prep_student{
  # my $param={teacherId=>'1004356', courseCode=>'0330'};
  # my $param={courseCode=>'0480', sectionId=>'17'};
  my $param={studentId=>'257750'};

    my $result = search_prep_student($dbh,$param);
     
my $stdList=$result->{'studentList'};
    foreach my $t (@$stdList){
        print $t->{"studentId"} , ", " , $t->{"firstName"} ,", " ,$t->{"lastName"},"\n"
    }


}

############################################################
sub testSearch_prep_course{
  # my $param={teacherId=>'1004356', courseCode=>'0330'};
  # my $param={courseCode=>'0480', sectionId=>'17'};
  my $param={};

    my $result = search_prep_course($dbh,$param);
     
my $stdList=$result->{'courseList'};
    foreach my $t (@$stdList){
        print $t->{"courseId"} , ", " , $t->{"courseName"} ,", " ,$t->{"courseCode"},"\n"
    }


}
############################################################
sub testSearch_prep_homeroom{
  # my $param={teacherId=>'1004356', courseCode=>'0330'};
  # my $param={courseCode=>'0480', sectionId=>'17'};
  my $param={};

    my $result = search_prep_homeroom($dbh,$param);
     
my $stdList=$result->{'homeroomList'};
    foreach my $t (@$stdList){
        print $t->{"homeroom"} ,"\n"
    }


}

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

sub testSearchTeacher{
  # my $param={teacherId=>'1004356', courseCode=>'0330'};
   my $param={courseCode=>'0480', sectionId=>'17'};
    my $result = search_teacher($dbh,$param);
     
my $stdList=$result->{'teacherList'};
    foreach my $t (@$stdList){
        print $t->{"teacherId"} , ", " , $t->{"firstName"} ,", " ,$t->{"lastName"},"\n"
    }


}
############################################################
sub testSearchCourse{
   #my $param={courseCode=>'4533', offset=>'0',count=>'5'};
   #my $param={teacherId=>'1004374',studentId=>'000556'};
   #my $param={studentId=>'000556'};
   #my $param={courseCode=>'0330'};
   my $param={teacherId=>'1004356', courseCode=>'0330'};
    my @stdList= search_course($dbh,$param);

    for( my $i=0; $i < 10 && $i <scalar(@stdList)  ; $i++){
        print @stdList[$i]->{"courseCode"} , ", " , @stdList[$i]->{"courseName"} ,", " ,@stdList[$i]->{"description"},"\n";
         my $sections=@stdList[$i]->{"sections"};
         foreach $s (@$sections){
          print "\tsection: ", $s->{'sectionId'} ."\n";
         }

    }


}
############################################################
sub testSearchHomeroom{
    my $param={};
    #my $param={homeroom=>'123'};
    my @stdList= search_homeroom($dbh,$param);

    for( my $i=0; $i < 10 && $i <scalar(@stdList)  ; $i++){
        print @stdList[$i]->{"homeroom"} ,"\n"
    }


}
sub testgetDistribution2Teacher{
    #my $params={teacherId=>'1004356',schoolYearId=>1};
    my $params={receiverId=>'248225',receiverType=>'students', schoolYearId=>1};
    my $result =getDistributions2ReceiverByType($dbh,$params);
    foreach my $r (@$result){
        print "$r->{'ISBN'} -- $r->{'distributed'} -- $r->{'ok'} -- $r->{'damaged'} -- $r->{'lost'} \n"
    }
}

############################################################
exit 0;

