#!/usr/bin/perl
use utf8;
use strict;
use warnings;
use Text::QRCode;
use GridFiller;
use GridFiller::Status;
use GridFiller::Chooser::Smarter;
use GridFiller::Result::Pango;
use feature 'say';
use open ':std',':locale';
use Log::Log4perl qw(:easy);
use Getopt::Long;

Log::Log4perl->easy_init($INFO);

#Log::Log4perl->get_logger('GridFiller')->level($INFO);
#Log::Log4perl->get_logger('GridFiller::Chooser')->level($DEBUG);
#Log::Log4perl->get_logger('GridFiller::Status')->level($DEBUG);
#Log::Log4perl->get_logger('GridFiller::Result')->level($DEBUG);

my ($data_file,$words_file,$level,$size,$output_file,$font_descr)
    =(undef,undef,'M',40,'/tmp/qr.png',undef);
{
my $p = Getopt::Long::Parser->new(
    config => [qw(
                     no_auto_abbrev
                     no_getopt_compat
                     no_gnu_compat
                     require_order
                     no_ignore_case
             )],
);
die unless $p->getoptions(
    'd|data=s' => \$data_file,
    'w|words=s' => \$words_file,
    'l|level=s' => \$level,
    's|size=i' => \$size,
    'o|output=s' => \$output_file,
    'f|font=s' => \$font_descr,
);
}

$level='M' unless $level=~m{^[LMH]$}i;

my $data = do {open my $fh,'<:utf8',$data_file;local $/;<$fh>};
my @words = do {open my $fh,'<:utf8',$words_file;<$fh>};chomp @words;

my $qr=Text::QRCode->new(
    level=>uc($level),
    mode=>'8-bit',
);

my $arr=$qr->plot($data);

my $result = GridFiller::Result::Pango->new({
    source_grid => $arr,
    cell_size => $size,
    ( $font_descr ? (font_description => $font_descr) : () ),
});

my $status=GridFiller::Status->new({
    words=>\@words,
    grid=> $arr,
    length => $result->length_closure,
    mode => 'longest',
});

my $chooser=GridFiller::Chooser::Smarter->new({
    status => $status,
});

my $filler=GridFiller->new({
    status => $status,
    chooser => $chooser,
    result => $result,
});

$filler->fill();

$result->save_png($output_file);

say '';
say 'Leftovers:';
say for @{$result->leftover_words};
