#!/usr/bin/perl
#package change_colours_imlib;

use strict;
use diagnostics;
use warnings;
use feature "say";
use Math::Trig;
use File::Spec;
use File::Basename;
use Tk;
use Tk::PNG;
use Tk::Canvas;
use Image::Size;
use Image::Imlib2;
use Math::Round;
use Data::Dumper qw(Dumper);
my $canvas2;
my ($directory,@files,$bg,$image_width,$image_height,@points,$canvas,$click,$track_name,$count,$new_x, $new_y);
my @dir_stack = ('.');  # Stack to store directories navigated
my $selected_file;
my @contents;
my $print_dir;
$click=0;
my $display_name="select a file";
my $filename="granger.png";
my $img;
my ($low,$high);
my $image_Imlib;
my $window;my $listbox;
my($min_r,$min_g, $min_b,$max_r,$max_g,$max_b,$max_a,$min_a,$img2,$x2,$y2,$x_prop,$r_new,$g_new,$b_new,$a_new);
my $swatch;
#sub run{
our $mw8a = MainWindow->new;
$mw8a->geometry("600x600+1200+1100");
$mw8a->title("Make a Path of Points");

$mw8a->Button(-font => '{Helvetica} 15', -width =>30,-text => "select a colour range from an image ", -command =>sub{
$window = $mw8a->Toplevel;
$listbox = $window->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se')->pack(-expand => 1, -fill => 'both');
$listbox->bind('<Double-Button-1>', \&select_item);
my $up_button = $window->Button(-font => '{Helvetica} 15', -text => 'UP', -command => \&go_up)->pack(-side => 'left', -padx => 5);
refresh_listbox();	
})->grid(qw/ -row 23 -column 0 -sticky n/);
$mw8a->Button(-font => '{Helvetica} 15', -width =>30,-text => "replacement colour", -command =>sub{&select_new_colour;})->grid(qw/ -row 24 -column 0 -sticky n/);
$mw8a->Button(-font => '{Helvetica} 15', -width =>30,-text => "replace range with selection", -command =>sub{&replace_colour_test;})->grid(qw/ -row 28 -column 0 -sticky n/);

my $label=$mw8a->Label(-font =>'{Helvetica} 15', -width =>40, -text =>"Left click for minimum, right click for maximum")->grid(qw/ -row 27 -column 0 -sticky n/);
$label=$mw8a->Label(-font =>'{Helvetica} 15', -width =>40, -text =>"put string here")->grid(qw/ -row 29 -column 0 -sticky n/);
$mw8a->Button(-font => '{Helvetica} 15', -width =>10,-text => "Close", -command =>sub{$mw8a->destroy;})->grid(qw/ -row 30 -column 0 -columnspan 2 -sticky n/);


MainLoop;

sub refresh_listbox {
my $dir = $dir_stack[-1];
#my $dir = grep { /.png/ } $dir_stack[-1];
    $listbox->delete(0, 'end');

    opendir(my $dh, $dir) or die "Can't open $dir: $!";
    @contents = readdir($dh);
    closedir($dh);

    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){
            $listbox->insert('end', $item);
        }
    }
}
sub select_item {
    my $selection = $listbox->get('active');
 my $path = File::Spec->catfile($dir_stack[-1], $selection);
    if (-d $path) {
        $selected_file = $path;
        print "Selected directory: $selected_file\n";  # Print the selected directory
        push @dir_stack, $path;  # Push selected directory to the stack
        refresh_listbox();
        $print_dir =$path;
    } elsif (-f $path) {
        $selected_file = $path;
        $bg=$path;
      $display_name = $bg;
      $window->destroy;
       
        print "Selected file: $bg\n";  # You can replace this with saving to a variable
&get_colour;
    }
}

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 get_colour{
my ($x, $y) = imgsize($bg);
my $myfile="$bg";
my $file_prop=$y/$x;
my $x_prop=1;
$img = Image::Imlib2->load($bg);
if ($x<400 || $x>600){
$x_prop=int(500/$x);
$x=$x*$x_prop;
$y=$x*$file_prop;
$img2=$img->create_scaled_image($x,$y);	
$myfile="temp/tmp_file.png";
$img2->save("$myfile");
say "it was small";
	}
	
my $window2 = $mw8a->Toplevel;	
$window2->title("select range");
$window2->geometry($x."x".$y."+1600+400");
my $image = $mw8a->Photo(-file => "$myfile");
# Create canvas
$canvas = $window2->Canvas(-width => $x, -height => $y)->grid(qw/ -row 0 -column 0  -sticky n/);
my $item = $canvas->createImage(0, 0, -image => $image, -anchor => 'nw', -state => 'disabled' );
# Bind mouse button-1 press event to handle_click function
$canvas->Tk::bind('<Button-1>', sub {
    #$minx=1;
    my $event = $canvas->XEvent;
    my ($x1, $y1) = ($event->x, $event->y);
$x1=int($x1/$x_prop);
$y1=int($y1/$x_prop);
($min_r,$min_g,$min_b,$min_a)=max_min_colours($x1,$y1);
say "min red is $min_r min alpha is $min_a ";
});
$canvas->Tk::bind('<Button-3>', sub {
    #$minx=2;
    my $event = $canvas->XEvent;
    my ($x1, $y1) = ($event->x, $event->y);
$x1=int($x1/$x_prop);
$y1=int($y1/$x_prop);
($max_r,$max_g,$max_b,$max_a)=max_min_colours($x1,$y1);
say "max red is $max_r max alpha is $max_a";
});
}

sub max_min_colours{
my ($x, $y) = @_;
say "x= $x: y= $y";
my ($r, $g, $b, $a) = $img->query_pixel($x, $y);
return($r, $g, $b,$a);	
}


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

sub get_pixel_colour {
my ($x, $y,$filename) = @_;
        my $img = Image::Imlib2->load($filename);
($r_new, $g_new, $b_new, $a_new) = $img->query_pixel($x, $y);
say "red is $r_new, green is $g_new, blue is  $b_new, alpha is $a_new";
return($r_new,$g_new,$b_new,$a_new);
}

sub replace_colour_test{
say "range min = $min_r,$min_g,$min_b\n";
say "range max = $max_r,$max_g,$max_b\n";
say "new= $r_new  $g_new  $b_new";	
#cropped_rotated_088G_100.png
my $input="$filename";
#my $input="temp/cropped_rotated_088G_100.png";
# Load the image
my $image3 = Image::Imlib2->load($input);
# Get the image dimensions
my $width = $image3->width;
my $height = $image3->height;

# Iterate over each pixel
for my $y (0 .. $height - 1) {
    for my $x (0 .. $width - 1) {
        my ($r, $g, $b, $a) = $image3->query_pixel($x, $y);

        if ($r >= $min_r && $r <= $max_r &&
            $g >= $min_g && $g <= $max_g &&
            $b >= $min_b && $b <= $max_b) {
            #$image->draw_point($x, $y, $r_new, $g_new, $b_new, $a);
            $image3->set_colour($r_new, $g_new, $b_new, $a_new);
            $image3->draw_point($x, $y);
        }
    }
}
$image3->set_quality(100);
# Save the modified image
$image3->save("output_new2.png");


	}


sub select_new_colour{
#for Imlib to get the pixel colour
$swatch='./granger.png';
say $swatch;
#my $swatch = Image::Imlib2->load("$swatch");
my ($image_width, $image_height) = imgsize($swatch);
my $colour_window = $mw8a->Toplevel;	
$colour_window->title("select replacement colour");
$colour_window->geometry($image_width."x".$image_height."+1000+400");
#my $image = $mw8a->Photo(-file => "temp/$tmp_file.png");
my $image = $mw8a->Photo(-file => "$swatch");
# Create canvas
#$canvas2 = $colour_window->Canvas(-width => $new_x, -height => $new_y)->grid(qw/ -row 0 -column 0  -sticky n/);
$canvas2 = $colour_window->Canvas(-width => $image_width, -height => $image_height)->grid(qw/ -row 0 -column 0  -sticky n/);
my $item = $canvas2->createImage(0, 0, -image => $image, -anchor => 'nw', -state => 'disabled' );
#Bind mouse button-1 press event to handle_click function
my $colour_window2 = $mw8a->Toplevel;	
$colour_window2->geometry("200x200+1940+400");
$canvas2->Tk::bind('<Button-1>', sub {
    my $event = $canvas2->XEvent;
    my ($x, $y) = ($event->x, $event->y);
say "x is $x, y is $y";
my ($r,$g,$b)=get_pixel_colour($x,$y,$swatch);
say "$r  $g  $b";
my $hex_color = rgb_to_hex($r,$g,$b);
$colour_window2->configure(-background => $hex_color);
});
}

#}
#1;







