#!/usr/bin/perl
#package roughly_crop;
use strict;
use diagnostics;
use warnings;
use feature "say";
use Math::Trig;
use File::Spec;
use File::Basename;
use Tk;
use Tk::PNG;
use Image::Size;
use Image::Imlib2;
use Math::Round;
use Data::Dumper qw(Dumper);

my ($directory,@files,$bg,$image_width,$image_height,@points,$canvas,$track_name,$count);
my @dir_stack = ('.');  # Stack to store directories navigated
my $selected_file;
my @contents;
my $print_dir;
my $click=0;
my $click2=0;
my $display_name="select a file";
my $display_name2="click top left then bottom right";
my $rect_id;
#sub run{
our $mw13 = MainWindow->new;
$mw13->geometry("600x300+700+800");
$mw13->title("make a rough crop");
my $label=$mw13->Label(-font => '{Helvetica} 15', -width =>30,-textvariable => \$display_name2)->grid(qw/ -row 10 -column 0 -sticky n/);
$mw13->Button(-font => '{Helvetica} 15', -width =>10,-text => "Show outline", -command =>sub{&draw;})->grid(qw/ -row 12 -column 0 -sticky w/);
$mw13->Button(-font => '{Helvetica} 15', -width =>10,-text => "delete outine", -command =>sub{&erase;})->grid(qw/ -row 12 -column 0 -sticky e/);
$mw13->Button(-font => '{Helvetica} 15', -width =>30,-text => "Crop Image", -command =>sub{&save_points;})->grid(qw/ -row 20 -column 0 -sticky n/);
#my $entry=$mw13->Entry(-font =>'{Helvetica} 15', -state=> 'disabled', -width =>32,-textvariable => \$display_name)->grid(qw/ -row 24 -column 0 -sticky n/);
$label=$mw13->Label(-font =>'{Helvetica} 15', -width =>40,-textvariable => \$display_name)->grid(qw/ -row 24 -column 0 -sticky n/);

$mw13->Button(-font => '{Helvetica} 15', -width =>10,-text => "Close", -command =>sub{say Dumper @points;$mw13->destroy;})->grid(qw/ -row 26 -column 0 -sticky n/);
my $entry = $mw13->Label(-font =>'{Helvetica} 20' , -textvariable => \$click2, -width =>8)->grid(qw/ -row 25 -column 0 -sticky n/);
####################
our $window = $mw13->Toplevel;
our $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();

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;
       &make_track;
        print "Selected file: $bg\n";  # You can replace this with saving to a variable
    }
}

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 save_points{
say "bg= $bg";
if ($points[0]{x}>$points[1]{x}){$display_name2="top left first then bottom right";return;}
if ($points[1]{y}<$points[0]{x}){$display_name2="top left first then bottom right";return;}
my $width=$points[1]{x}-$points[0]{x};
my $height=$points[1]{y}-$points[0]{y};
my $x=$points[0]{x};
my $y=$points[0]{y};
if(!$bg){return;}
if(!@points){say " there are no points";return;}
say  Dumper @points;
my ($file,$directories,$suffix) = fileparse($bg, qr/\.[^.]*$/);###########
my @words= split /\//,$directories;# split directory path on "/"
my $scene=$words[0];

say Dumper @words;
say $scene;
say $file;
say "dir = $scene file =  $file";
open(my $fh, '>', "$scene/$file") or die "Could not open file '$scene/$file' $!";
print $fh "x,$points[0]{x},y,$points[0]{y}\n";
print $fh "x,$points[1]{x},y,$points[1]{y}\n";
close $fh;	
$display_name= "wrote .\/$scene/$file";
#my $image =Image::Imlib2->new_transparent($image_width,$image_height);
my $image=Image::Imlib2->load($bg);
my $image2=$image->crop($x,$y,$width,$height);
my $text= join "",$scene,"/",$file,"-cropped",$width,"x",$height,".png";
say "text= $text";
$image2->save($text);
$image2=undef;
$image=undef;
$display_name="wrote $text";
$display_name2="done";
}


sub make_track{
($image_width, $image_height) = imgsize($bg);
my $track_window = $mw13->Toplevel;	
my $geom=$image_width."x".$image_height."+1000+400";
say $geom;
$track_window->title("select points");
$track_window->geometry($geom);
my $image = $mw13->Photo(-file => "$bg");
# Create canvas
$canvas = $track_window->Canvas(-width => $image_width, -height => $image_height)->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 {
    my $event = $canvas->XEvent;
    my ($x, $y) = ($event->x, $event->y);
    handle_click($x, $y);
});

	}
	
sub handle_click {
    my ($x, $y) = @_;
if ($click<2){
$points[$click]{x}=$x;
$points[$click]{y}=$y;
$canvas->createOval($x-3, $y-3, $x+3, $y+3, -fill => 'red');
}    # Draw a dot at the clicked location on the Canvas
 else{
my $x1=$points[0]{x};
my $y1=$points[0]{y};

$canvas->createOval($x1-3, $y1-3, $x1+3, $y1+3, -fill => 'white');
$canvas->createOval($x-3, $y-3, $x+3, $y+3, -fill => 'red');
$points[0]{x}=$points[1]{x};
$points[0]{y}=$points[1]{y};
$points[1]{x}=$x;
$points[1]{y}=$y;	 
}  
$click++;

if ($click/2==int($click/2)){$click2=1;}
else{$click2=0;}

}

sub draw{
if($rect_id){$canvas->delete($rect_id);}
$rect_id = $canvas->createRectangle($points[0]{x},$points[0]{y},$points[1]{x},$points[1]{y}, -outline => 'black');

	}
sub erase{
$canvas->delete($rect_id);	
	}

#}
#1;






