#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use File::Path qw(make_path);
use File::Spec;
use File::Basename;
use Image::Imlib2;
use feature "say";

my @dir_stack = ('.');  # Stack to store directories navigated
my ($selected_file, $selected_dir, @contents, $print_dir, @files, $text, $dir, $blank, $img, $img_dir);
my $mw = MainWindow->new;
$mw->title("BLUR IMAGES"); 
$mw->geometry("1200x900+1100+500");
my $font_large = ['Arial', 20];
my $font = '{Helvetica} 20';
my $label = $mw->Label(-font => $font, -text => "BLUR SELECTED FILE OR ALL IN DIRECTORY:\n", -width => 28)->grid(qw/ -row 0 -column 0 -columnspan 3 -sticky nsew/);
my $frame = $mw->Frame()->grid(qw/ -row 2 -column 0  -sticky w/); 
my $frame2 = $mw->Frame()->grid(qw/ -row 4 -column 0 -sticky w/);
my $frame3 = $mw->Frame()->grid(qw/ -row 2 -column 1 -rowspan 6 -columnspan 2 -sticky w/);
my $button = $mw->Button(-font => $font, -text => 'GO UP', -justify => 'left', -width => 5, -command => sub { &GO_UP })->grid(qw/ -row 3 -column 0 -sticky w/);
$button = $mw->Button(-font => $font, -text => 'QUIT', -justify => 'left', -width => 5, -command => sub { $mw->destroy() })->grid(qw/ -row 5 -column 0 -sticky w/);
my $listbox = $frame->Scrolled('Listbox', -font => $font, -scrollbars => 'se', -width => 30)->grid(qw/ -row 0 -column 0 -sticky w/);
my $message_box = $frame2->Scrolled('Listbox', -font => $font, -scrollbars => 'se', -width => 30, -height => 6)->grid(qw/ -row 0 -column 1  -sticky w/); 
$listbox->bind('<Double-Button-1>', \&select_item);

my $save_directory = "blur";
my $output = "blurred_";          # editable prefix, default "blurred_"
my $blur_amount = 1;

$label = $frame3->Label(-font => $font, -text => "save directory:", -width => 15)->grid(qw/ -row 0 -column 0 -sticky nsew/);
my $entry = $frame3->Entry(-font => $font, -textvariable => \$save_directory, -width => 20)->grid(qw/ -row 0 -column 1 -sticky nsew/);
$label = $frame3->Label(-font => $font, -text => 'input_file', -justify => 'left', -width => 15)->grid(qw/ -row 1 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$selected_file, -width => 20)->grid(qw/ -row 1 -column 1  -sticky nsew/);
$label = $frame3->Label(-font => $font, -text => 'blur prefix', -justify => 'left', -width => 15)->grid(qw/ -row 2 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$output, -width => 20)->grid(qw/ -row 2 -column 1 -sticky nsew/);
$label = $frame3->Label(-font => $font, -text => 'Blur amount', -justify => 'left', -width => 15)->grid(qw/ -row 3 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$blur_amount, -width => 20)->grid(qw/ -row 3 -column 1 -sticky nsew/);

$button = $frame3->Button(-font => $font, -text => 'Make Blur', -justify => 'left', -width => 15,
    -command => sub { blur_single() })->grid(qw/ -row 5 -column 0 -sticky nsew/);
$button = $frame3->Button(-font => $font, -text => 'Blur All in Dir', -justify => 'left', -width => 15,
    -command => sub { blur_all() })->grid(qw/ -row 5 -column 1 -sticky nsew/);

&refresh_listbox;
MainLoop;

sub refresh_listbox {
    my $dir = $dir_stack[-1];
    $listbox->delete(0, 'end');
    opendir(my $dh, $dir) or die "Can't open $dir: $!";
    @contents = readdir($dh);
    closedir($dh);
    @contents = sort { lc($a) cmp lc($b) } @contents;
    foreach my $item (@contents) {
        next if $item =~ /^\./;  # skip hidden files/directories
        my $path = File::Spec->catfile($dir, $item);
        if (-d $path) {
            $listbox->insert('end', $item);
            $listbox->itemconfigure('end', -foreground => 'blue');  # Apply blue color to directory item
        } elsif ($item =~ /\.png$/i || $item =~ /\.jpg$/i || $item =~ /\.jpeg$/i) {
            $listbox->insert('end', $item);
        }
    }
}

sub select_item {
    my $selection = $listbox->get('active');
    my $path = File::Spec->catfile($dir_stack[-1], $selection);
    if (-d $path) {
        push @dir_stack, $path;  # Push selected directory to the stack
        refresh_listbox();
        $selected_dir = $path;
        $text = "Selected directory: $selected_dir";
        $message_box->delete('0', 'end');
        $message_box->insert('0', $text);
    } elsif (-f $path) {
        $selected_file = $path;
        $text = "selected file = $selected_file";
        $message_box->insert('end', $text);
    }
    refresh_listbox();
}

sub GO_UP {
    pop @dir_stack if @dir_stack > 1;  # Pop the top directory from the stack if not already at the root
    refresh_listbox();
}

sub numerically {
    my ($a_num) = $a =~ /(\d+)/;
    my ($b_num) = $b =~ /(\d+)/;
    $a_num //= 0;
    $b_num //= 0;
    return $a_num <=> $b_num;
}

# Generate output basename: prefix the string to the original basename
# (directory path is stripped). Default is "blurred_".
sub make_output_name {
    my ($input_path, $suffix) = @_;
    my $base = basename($input_path);
    return $suffix . $base;
}

sub blur_me {
    my ($input_file, $output_file, $max_blur_radius, $dir_name) = @_;
    make_path($dir_name) unless -d $dir_name;
    # Load the original image
    my $original = Image::Imlib2->load($input_file);
    unless ($original) {
        $message_box->insert('end', "Failed to load $input_file");
        return;
    }
    $original->has_alpha(1);
    $original->blur($max_blur_radius);
    my $save_path = File::Spec->catfile($dir_name, $output_file);
    $original->save($save_path);
    $message_box->insert('end', "Saved $save_path");
}

sub blur_single {
    unless ($selected_file && -f $selected_file) {
        $message_box->insert('end', "No file selected");
        return;
    }
    my $outname = make_output_name($selected_file, $output);
    blur_me($selected_file, $outname, $blur_amount, $save_directory);
}

sub blur_all {
    my $dir = $dir_stack[-1];
    opendir(my $dh, $dir) or do {
        $message_box->insert('end', "Can't open $dir");
        return;
    };
    my @images = grep {
        /\.(png|jpg|jpeg)$/i && -f File::Spec->catfile($dir, $_)
    } readdir($dh);
    closedir($dh);

    $message_box->delete(0, 'end');
    $message_box->insert('end', "Blurring " . scalar(@images) . " image(s) in $dir using prefix '$output'");

    foreach my $img (@images) {
        my $full = File::Spec->catfile($dir, $img);
        my $outname = make_output_name($full, $output);
        blur_me($full, $outname, $blur_amount, $save_directory);
    }
    $message_box->insert('end', "Done.");
}
