#!/usr/bin/perl
use strict;
use warnings;
use feature "say";
use File::Spec;
use Tk;
use Tk::PNG;
use Image::Size;
use Image::Imlib2;
use File::Basename;
my $mw = MainWindow->new;
$mw->geometry("600x700+1200+1000");
$mw->title("Change Colour");

my @dir_stack = ('.');
my $bg;                  # currently selected image path
#my $swatch = "granger.png";
my $swatch_name = "granger.png";   # always the name to search for
my $swatch_path;                   # resolved full path (or undef)
my ($min_r, $min_g, $min_b, $min_a);
my ($max_r, $max_g, $max_b, $max_a);
my ($r_new, $g_new, $b_new, $a_new);

my $range_window;        # min/max colour picker
my $colour_window;       # replacement colour picker
my $preview_window;      # small colour preview
my $preserve_alpha = 1;   # 1 = keep original transparency, 0 = use swatch alpha
# --- Buttons ---
$mw->Button(
    -font => '{Helvetica} 15', -width => 32,
    -text => "select a colour range from an image",
    -command => sub { open_file_browser() }
)->grid(-row => 0, -column => 0, -sticky => 'n', -pady => 4);

$mw->Button(
    -font => '{Helvetica} 15', -width => 32,
    -text => "replacement colour",
    -command => \&select_new_colour
)->grid(-row => 1, -column => 0, -sticky => 'n', -pady => 4);

$mw->Button(
    -font => '{Helvetica} 15', -width => 32,
    -text => "replace range with flat colour",
    -command => sub { replace_colour(0) }   # 0 = flat
)->grid(-row => 2, -column => 0, -sticky => 'n', -pady => 4);

$mw->Button(
    -font => '{Helvetica} 15', -width => 32,
    -text => "replace range keeping tones",
    -command => sub { replace_colour(1) }   # 1 = keep tones
)->grid(-row => 3, -column => 0, -sticky => 'n', -pady => 4);

$mw->Checkbutton(
    -font    => '{Helvetica} 15',
    -text    => "preserve original transparency",
    -variable => \$preserve_alpha,
    -onvalue  => 1,
    -offvalue => 0,
)->grid(-row => 4, -column => 0, -sticky => 'n', -pady => 4);

$mw->Label(
    -font => '{Helvetica} 15', -width => 42,
    -text => "Left click for minimum, right click for maximum"
)->grid(-row => 5, -column => 0, -sticky => 'n', -pady => 8);


$mw->Button(
    -font => '{Helvetica} 15', -width => 32,
    -text => "batch flat colour (selected image's dir)",
    -command => sub {
        my $dir = $bg ? File::Basename::dirname($bg) : '.';
        process_directory($dir, 0);
    }
)->grid(-row => 6, -column => 0, -sticky => 'n', -pady => 4);

$mw->Button(
    -font => '{Helvetica} 15', -width => 32,
    -text => "batch keep tones (selected image's dir)",
    -command => sub {
        my $dir = $bg ? File::Basename::dirname($bg) : '.';
        process_directory($dir, 1);
    }
)->grid(-row => 7, -column => 0, -sticky => 'n', -pady => 4);


$mw->Button(
    -font => '{Helvetica} 15', -width => 10,
    -text => "Close",
    -command => sub { $mw->destroy }
)->grid(-row => 8, -column => 0, -sticky => 'n', -pady => 10);


MainLoop;

# ---------------------------------------------------------------------------
sub open_file_browser {
    my $window = $mw->Toplevel;
    my $listbox = $window->Scrolled('Listbox',
        -font => '{Helvetica} 20', -scrollbars => 'se'
    )->pack(-expand => 1, -fill => 'both');

    $listbox->bind('<Double-Button-1>', sub { select_item($listbox, $window) });
    $window->Button(
        -font => '{Helvetica} 15', -text => 'UP',
        -command => sub { go_up($listbox) }
    )->pack(-side => 'left', -padx => 5);

    refresh_listbox($listbox);
}

sub refresh_listbox {
    my ($listbox) = @_;
    my $dir = $dir_stack[-1];
    $listbox->delete(0, 'end');

    opendir(my $dh, $dir) or do {
        warn "Can't open $dir: $!";
        return;
    };
    my @contents = readdir($dh);
    closedir($dh);

    for my $item (@contents) {
        next if $item =~ /^\./;
        my $path = File::Spec->catfile($dir, $item);
        if (-d $path) {
            $listbox->insert('end', $item);
            $listbox->itemconfigure('end', -foreground => 'blue');
        }
        elsif ($item =~ /\.(png|jpg|jpeg)$/i) {
            $listbox->insert('end', $item);
        }
    }
}

sub select_item {
    my ($listbox, $window) = @_;
    my $selection = $listbox->get('active') or return;
    my $path = File::Spec->catfile($dir_stack[-1], $selection);

    if (-d $path) {
        push @dir_stack, $path;
        refresh_listbox($listbox);
    }
    elsif (-f $path) {
        # Close any previous picker windows and clear state
        close_pickers();
        clear_colour_state();

        $bg = $path;
        $window->destroy;
        say "Selected file: $bg";
        get_colour();
    }
}

sub go_up {
    my ($listbox) = @_;
    pop @dir_stack if @dir_stack > 1;
    refresh_listbox($listbox);
}

sub close_pickers {
    $range_window->destroy   if defined $range_window   && Tk::Exists($range_window);
    $colour_window->destroy  if defined $colour_window  && Tk::Exists($colour_window);
    $preview_window->destroy if defined $preview_window && Tk::Exists($preview_window);
    undef $range_window;
    undef $colour_window;
    undef $preview_window;
}

sub clear_colour_state {
    ($min_r, $min_g, $min_b, $min_a) = ();
    ($max_r, $max_g, $max_b, $max_a) = ();
    ($r_new, $g_new, $b_new, $a_new) = ();
}

# ---------------------------------------------------------------------------
sub get_colour {
    return warn "No image selected" unless $bg && -f $bg;

    close_pickers();   # extra safety

    mkdir "temp" unless -d "temp";

    my ($x, $y) = imgsize($bg) or do {
        warn "Cannot read image size: $bg";
        return;
    };

    my $img = Image::Imlib2->load($bg) or do {
        warn "Cannot load image: $bg";
        return;
    };

    my $display_file = $bg;
    my $scale = 1;

    if ($x < 600) {
        $scale = int(600 / $x) || 1;
        $x *= $scale;
        $y *= $scale;
        my $scaled = $img->create_scaled_image($x, $y);
        $display_file = "temp/tmp_file.png";
        $scaled->save($display_file) or warn "Failed to save scaled image";
    }

    $range_window = $mw->Toplevel;
    $range_window->title("select range");
    $range_window->geometry("${x}x${y}+1600+400");

    my $photo = $mw->Photo(-file => $display_file);
    my $canvas = $range_window->Canvas(-width => $x, -height => $y)
        ->grid(-row => 0, -column => 0, -sticky => 'n');
    $canvas->createImage(0, 0, -image => $photo, -anchor => 'nw', -state => 'disabled');

    $canvas->Tk::bind('<Button-1>', sub {
        my $e = $canvas->XEvent;
        my $px = int($e->x / $scale);
        my $py = int($e->y / $scale);
        ($min_r, $min_g, $min_b, $min_a) = $img->query_pixel($px, $py);
        say "min: r=$min_r g=$min_g b=$min_b a=$min_a";
    });

    $canvas->Tk::bind('<Button-3>', sub {
        my $e = $canvas->XEvent;
        my $px = int($e->x / $scale);
        my $py = int($e->y / $scale);
        ($max_r, $max_g, $max_b, $max_a) = $img->query_pixel($px, $py);
        say "max: r=$max_r g=$max_g b=$max_b a=$max_a";
    });
}

# ---------------------------------------------------------------------------


sub select_new_colour {
    close_pickers();

    # Always search by the original name, not a previously resolved path
    $swatch_path = find_file($swatch_name) or return;

    my ($w, $h) = imgsize($swatch_path) or do {
        warn "Cannot read swatch size: $swatch_path";
        return;
    };

    $colour_window = $mw->Toplevel;
    $colour_window->title("select replacement colour");
    $colour_window->geometry("${w}x${h}+1000+400");

    my $photo = $mw->Photo(-file => $swatch_path);
    my $canvas = $colour_window->Canvas(-width => $w, -height => $h)
        ->grid(-row => 0, -column => 0, -sticky => 'n');
    $canvas->createImage(0, 0, -image => $photo, -anchor => 'nw', -state => 'disabled');

    $preview_window = $mw->Toplevel;
    $preview_window->geometry("200x200+1940+400");
    $preview_window->title("preview");

    $canvas->Tk::bind('<Button-1>', sub {
        my $e = $canvas->XEvent;
        ($r_new, $g_new, $b_new, $a_new) = get_pixel_colour($e->x, $e->y, $swatch_path);
        my $hex = rgb_to_hex($r_new, $g_new, $b_new);
        $preview_window->configure(-background => $hex);
        say "new colour: $r_new $g_new $b_new ($hex)";
    });
}

sub find_file {
    my $filename = shift or do {
        warn "find_file: no filename given";
        return;
    };

    # If a full path was somehow passed, reduce it to the basename
    $filename =~ s{.*/}{};

    my @paths = `locate -b "\\$filename" 2>/dev/null`;
    chomp @paths;
    @paths = grep { -f $_ && -r $_ } @paths;

    unless (@paths) {
        warn "Could not find '$filename' via locate";
        return;
    }

    my $path = $paths[0];
    say "Using image: $path";
    return $path;
}













sub get_pixel_colour {
    my ($x, $y, $filename) = @_;
    my $img = Image::Imlib2->load($filename) or do {
        warn "Cannot load $filename";
        return (0, 0, 0, 255);
    };
    return $img->query_pixel($x, $y);
}

sub rgb_to_hex {
    my ($r, $g, $b) = @_;
    return sprintf("#%02X%02X%02X", $r // 0, $g // 0, $b // 0);
}

# ---------------------------------------------------------------------------
sub replace_colour {
    my ($keep_tones) = @_;

    unless (defined $min_r && defined $max_r && defined $r_new && $bg && -f $bg) {
        warn "Need min/max range, replacement colour, and an image first";
        return;
    }

    say "range min = $min_r,$min_g,$min_b";
    say "range max = $max_r,$max_g,$max_b";
    say "new       = $r_new,$g_new,$b_new";
    say $keep_tones ? "mode: keep tones" : "mode: flat colour";

    my $image = Image::Imlib2->load($bg) or do {
        warn "Cannot load $bg";
        return;
    };

    my $width  = $image->width;
    my $height = $image->height;

    my ($lum_min, $lum_max, $lum_span);
    if ($keep_tones) {
        $lum_min  = luminance($min_r, $min_g, $min_b);
        $lum_max  = luminance($max_r, $max_g, $max_b);
        $lum_span = $lum_max - $lum_min;
        $lum_span = 1 if $lum_span == 0;
    }

    for my $y (0 .. $height - 1) {
        for my $x (0 .. $width - 1) {
            my ($r, $g, $b, $a) = $image->query_pixel($x, $y);

            if ($r >= $min_r && $r <= $max_r &&
                $g >= $min_g && $g <= $max_g &&
                $b >= $min_b && $b <= $max_b) {

                my ($nr, $ng, $nb);

                if ($keep_tones) {
                    my $lum = luminance($r, $g, $b);
                    my $t   = ($lum - $lum_min) / $lum_span;   # 0..1
                    $nr = int($r_new * (0.4 + 0.8 * $t));
                    $ng = int($g_new * (0.4 + 0.8 * $t));
                    $nb = int($b_new * (0.4 + 0.8 * $t));
                }
                else {
                    $nr = $r_new;
                    $ng = $g_new;
                    $nb = $b_new;
                }

                $nr = 0 if $nr < 0; $nr = 255 if $nr > 255;
                $ng = 0 if $ng < 0; $ng = 255 if $ng > 255;
                $nb = 0 if $nb < 0; $nb = 255 if $nb > 255;

                #$image->set_colour($nr, $ng, $nb, $a_new // $a);
                #$image->draw_point($x, $y);
                my $alpha = $preserve_alpha ? $a : ($a_new // $a);
                $image->set_colour($nr, $ng, $nb, $alpha);
                $image->draw_point($x, $y);
                 
            }
        }
    }

 $image->set_quality(100);
my $out = $keep_tones ? "output_tones.png" : "output_flat.png";

# Save (ignore the sometimes-unreliable return value)
$image->save($out);

# Confirm the file exists and is non-empty
if (-f $out && -s $out) {
    say "Saved $out";
}
else {
    warn "Failed to save $out";
    return;
}

}

sub luminance {
    my ($r, $g, $b) = @_;
    return 0.299 * $r + 0.587 * $g + 0.114 * $b;
}

# ---------------------------------------------------------------------------


sub process_directory {
    my ($dir, $keep_tones) = @_;

    unless (defined $min_r && defined $max_r && defined $r_new) {
        warn "Set the colour range and replacement colour first";
        return;
    }

    opendir(my $dh, $dir) or do {
        warn "Cannot open directory $dir: $!";
        return;
    };

    my @files = grep { /\.(png|jpg|jpeg)$/i && -f File::Spec->catfile($dir, $_) } readdir($dh);
    closedir($dh);

    unless (@files) {
        warn "No images found in $dir";
        return;
    }

    # Optional: write results to a sub-folder so originals stay safe
    my $outdir = File::Spec->catdir($dir, "recoloured");
    mkdir $outdir unless -d $outdir;

    for my $file (@files) {
        my $in  = File::Spec->catfile($dir, $file);
        my $out = File::Spec->catfile($outdir, $file);

        say "Processing $in";

        my $image = Image::Imlib2->load($in) or do {
            warn "Cannot load $in – skipping";
            next;
        };

        my $width  = $image->width;
        my $height = $image->height;

        my ($lum_min, $lum_max, $lum_span);
        if ($keep_tones) {
            $lum_min  = luminance($min_r, $min_g, $min_b);
            $lum_max  = luminance($max_r, $max_g, $max_b);
            $lum_span = $lum_max - $lum_min || 1;
        }

        for my $y (0 .. $height - 1) {
            for my $x (0 .. $width - 1) {
                my ($r, $g, $b, $a) = $image->query_pixel($x, $y);

                if ($r >= $min_r && $r <= $max_r &&
                    $g >= $min_g && $g <= $max_g &&
                    $b >= $min_b && $b <= $max_b) {

                    my ($nr, $ng, $nb);
                    if ($keep_tones) {
                        my $lum = luminance($r, $g, $b);
                        my $t   = ($lum - $lum_min) / $lum_span;
                        $nr = int($r_new * (0.4 + 0.8 * $t));
                        $ng = int($g_new * (0.4 + 0.8 * $t));
                        $nb = int($b_new * (0.4 + 0.8 * $t));
                    }
                    else {
                        ($nr, $ng, $nb) = ($r_new, $g_new, $b_new);
                    }

                    $nr = 0 if $nr < 0; $nr = 255 if $nr > 255;
                    $ng = 0 if $ng < 0; $ng = 255 if $ng > 255;
                    $nb = 0 if $nb < 0; $nb = 255 if $nb > 255;

                    my $alpha = $preserve_alpha ? $a : ($a_new // $a);
                    $image->set_colour($nr, $ng, $nb, $alpha);
                    $image->draw_point($x, $y);
                }
            }
        }

        $image->set_quality(100);
        $image->save($out);
        if (-f $out && -s $out) {
            say "  → $out";
        }
        else {
            warn "  Failed to save $out";
        }
    }

    say "Finished directory $dir";
}
