#!/usr/bin/perl

use Modern::Perl;

use C4::Branch;
use C4::Context;
use Koha::Calendar;
use Time::Progress;

my $dbh = C4::Context->dbh;
$dbh->{AutoCommit} = 0;
$|++;
my $with_patch = $ARGV[0] // 0;

my $branchcode = 'my_tmp_br';
C4::Branch::ModBranch({
    branchcode => $branchcode,
    branchname => $branchcode,
});

$dbh->do(q|DELETE FROM special_holidays|);
my $num_dt = 1000;
for my $i ( 1 .. $num_dt ) {
    print "\rInserting random datetime $i/$num_dt";
    my $day = int(rand(27))+1;
    my $month = int(rand(11))+1;
    my $year = 2000 + int(rand(15));
    $dbh->do(
        q|INSERT INTO special_holidays (branchcode,day,month,year,isexception,title,description) values (?,?,?,?,?,?,?)|,
        {}, ($branchcode, $day, $month, $year, 0, '', '')
    );
}

say "\tDONE";

my $num_it = 3;
my $p = new Time::Progress;
$p->restart;
unless ( $with_patch ) {
    for my $i ( 1 .. $num_it ) {
        print "\rGenerating Calendar $i/$num_it";
        my $calendar = Koha::Calendar->new(branchcode => $branchcode);
    }
} else {
    for my $i ( 1 .. $num_it ) {
        print "\rGenerating Calendar $i/$num_it";
        my $calendar = Koha::Calendar->new(branchcode => $branchcode);
        $calendar->single_holidays;
        $calendar->exception_holidays;
    }
}
say "\tDONE";
$p->stop;
say $p->elapsed_str;

