#!/usr/bin/perl
use Modern::Perl;
use List::Util qw( shuffle );

use C4::Members;
use C4::Context;

my $number_of_patrons_to_create = 0; # CHANGE ME


my $dbh = C4::Context->dbh;

my $categories = $dbh->selectcol_arrayref(q|
    SELECT categorycode from categories
|);

my $branches = $dbh->selectcol_arrayref(q|
    SELECT branchcode from branches
|);

for my $i ( 1..$number_of_patrons_to_create ) {
    say "Inserting patron $i";
    $dbh->do(q|
        INSERT INTO borrowers(
            cardnumber,
            surname,
            firstname,
            address,
            city,
            email,
            dateofbirth,
            branchcode,
            categorycode,
            userid,
            sort1,
            sort2
        ) VALUES (
            ?, ?, ?, ?, ?, ?,
            FROM_UNIXTIME(
                UNIX_TIMESTAMP('1970-01-01 00:00:00') + FLOOR(0 + (RAND() * 500000000))
            ),
            ?, ?, ?, ?, ?
        )
    |, {}, (
        r(16),r(10),r(10),r(20), r(10), r(5) . '@' . r(5) . '.org', sh(@$branches), sh(@$categories), r(30), r(30), r(30)
    ));
}

sub sh {
    my @a = shuffle @_;
    return $a[0];
}

sub r {
    my $nb_chars = shift || 10;
    my @chars = ("A".."Z", "a".."z", " ", "-", "_", ".");
    my $string;
    $string .= $chars[rand @chars] for 1..$nb_chars;
    return $string;
}
