#!/usr/bin/perl
#package image_position;
use strict;
use warnings;
use Tk;
use Tk::PNG;
use Image::Imlib2;
use Image::Size;
use feature "say";
use Math::Round;
use Math::Trig;
#use Data::Dumper qw(Dumper);
my @dir_stack = ('.');  # Stack to store directories navigated
my $selected_file;
my @contents;
my $print_dir;
my $bg;
my $current_item=1;
my ($chk,@images,$num,$layers,$level,@photo,@items,$scene_name,$filename,$index,@dist,$ct,@display);
my $selection="blank/imageBOX2286.png";##<---------------
my $multi=0;
$images[0]{image}="blank/imageBOX2286.png";
$layers=1;
my $string="select an image( all the needed files should be in the selected directory)\n The display (grey area) is 1170x658 pixels ";
# at present it might be the order they are selected, which it shouldn't be.
my $string2="higher numbered levels are on top\n ";
#sub run{
our $mw1 = MainWindow->new;
$mw1->geometry("2286x1525+768+432");
$mw1->title("double click to select image");

$mw1->Label(-font => '{Helvetica} 15', -width =>20,-text => "levels for multiplane")->grid(qw/ -row 16 -column 2 -columnspan 3 -sticky w/);
$mw1->Label(-font => '{Helvetica} 15', -width =>10,-text => "scene name")->grid(qw/ -row 18 -column 0 -sticky e/);
my $entry = $mw1->Label(-font => '{Helvetica} 15',  -textvariable => \$scene_name, -width =>10)->grid(qw/ -row 18 -column 1 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>2,-text => "-", -command =>sub{$layers=$layers-1;if($layers<1){$layers=1}})->grid(qw/ -row 18 -column 1 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$layers, -width =>6)->grid(qw/ -row 18 -column 2 -sticky n/);
$mw1->Button(-font => '{Helvetica} 15', -width =>2,-text => "+", -command =>sub{$layers=$layers+1;if($layers>6){$layers=6};})->grid(qw/ -row 18 -column 2 -sticky w/);
$mw1->Label(-font =>'{Helvetica} 15', -text => "start")->grid(qw/ -row 18 -column 2 -sticky e/);
$mw1->Label(-font =>'{Helvetica} 15', -text => "end")->grid(qw/ -row 18 -column 3 -sticky e/);
$mw1->Button(-font => '{Helvetica} 15', -width =>10, -text => "image 1", -command =>sub{$current_item=2;$level=1;&select_item();})->grid(qw/ -row 22 -column 0 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[1]{image}, -width =>30)->grid(qw/ -row 22 -column 1 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6,-text => "multi", -command =>sub{$level=1;if($layers>6){$layers=6};$multi=1;&multi();})->grid(qw/ -row 22 -column 4 -sticky w/);

$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[1]{start_x}, -width =>6)->grid(qw/ -row 22 -column 2 -sticky e/);

$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=1;&find_position(2,"start")})->grid(qw/ -row 22 -column 2 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=1;&find_position(2,"end")})->grid(qw/ -row 22 -column 3 -sticky w/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[1]{end_x}, -width =>6)->grid(qw/ -row 22 -column 3 -sticky e/);

$mw1->Button(-font => '{Helvetica} 15', -width =>10, -text => "image 2", -command =>sub{$current_item=3;$level=2;&select_item();})->grid(qw/ -row 23 -column 0 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[2]{image}, -width =>30)->grid(qw/ -row 23 -column 1 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=2;&find_position(3,"start")})->grid(qw/ -row 23 -column 2 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=2;&find_position(3,"end")})->grid(qw/ -row 23 -column 3 -sticky w/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[2]{start_x}, -width =>6)->grid(qw/ -row 23 -column 2 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[2]{end_x}, -width =>6)->grid(qw/ -row 23 -column 3 -sticky e/);

$mw1->Button(-font => '{Helvetica} 15', -width =>10,-text => "image 3", -command =>sub{$current_item=4;$level=3;&select_item();})->grid(qw/ -row 24 -column 0 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[3]{image}, -width =>30)->grid(qw/ -row 24 -column 1 -sticky w/);

$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=3;&find_position(4,"start")})->grid(qw/ -row 24 -column 2 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=3;&find_position(4,"end")})->grid(qw/ -row 24 -column 3 -sticky w/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[3]{start_x}, -width =>6)->grid(qw/ -row 24 -column 2 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[3]{end_x}, -width =>6)->grid(qw/ -row 24 -column 3 -sticky e/);

$mw1->Button(-font => '{Helvetica} 15', -width =>10,-text => "image 4", -command =>sub{$current_item=5;$level=4;&select_item();})->grid(qw/ -row 25 -column 0 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[4]{image}, -width =>30)->grid(qw/ -row 25 -column 1 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=4;&find_position(5,"start")})->grid(qw/ -row 25 -column 2 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=4;&find_position(5,"end")})->grid(qw/ -row 25 -column 3 -sticky w/);

$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[4]{start_x}, -width =>6)->grid(qw/ -row 25 -column 2 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[4]{end_x}, -width =>6)->grid(qw/ -row 25 -column 3 -sticky e/);

$mw1->Button(-font => '{Helvetica} 15', -width =>10,-text => "image 5", -command =>sub{$current_item=6;$level=5;&select_item();})->grid(qw/ -row 26 -column 0 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[5]{image}, -width =>30)->grid(qw/ -row 26 -column 1 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=5;&find_position(6,"start")})->grid(qw/ -row 26 -column 2 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=5;&find_position(6,"end")})->grid(qw/ -row 26 -column 3 -sticky w/);

$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[5]{start_x}, -width =>6)->grid(qw/ -row 26 -column 2 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[5]{end_x}, -width =>6)->grid(qw/ -row 26 -column 3 -sticky e/);

$mw1->Button(-font => '{Helvetica} 15', -width =>10,-text => "image 6", -command =>sub{$current_item=7;$level=6;&select_item();})->grid(qw/ -row 27 -column 0 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[6]{image}, -width =>30)->grid(qw/ -row 27 -column 1  -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=6;&find_position(7,"start")})->grid(qw/ -row 27 -column 2 -sticky w/);
$mw1->Button(-font => '{Helvetica} 15', -width =>6, -text => "get pos", -command =>sub{$level=6;&find_position(7,"end")})->grid(qw/ -row 27 -column 3 -sticky w/);

$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[6]{start_x}, -width =>6)->grid(qw/ -row 27 -column 2 -sticky e/);
$entry = $mw1->Entry(-font => '{Helvetica} 15', -textvariable => \$images[6]{end_x}, -width =>6)->grid(qw/ -row 27 -column 3 -sticky e/);
$mw1->Button(-font => '{Helvetica} 15', -width =>10,-text => "CLOSE", -command =>sub{$mw1->destroy();})->grid(qw/ -row 50 -column 0 -sticky e/);
our $frame = $mw1->Frame()->grid(qw/ -row 19 -column 5 -rowspan 30 -sticky w/); 
our $listbox = $frame->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width=>30)->grid(qw/ -row 19 -column 5  -sticky w/); 
my $up_button = $frame->Button(-font => '{Helvetica} 15', -text => 'UP', -command => \&go_up)->grid(qw/ -row 50 -column 5 -rowspan 30 -sticky w/); 
$entry =$mw1->Label(-font => '{Helvetica} 20', -width =>80, -textvariable => \$string)->grid(qw/ -column 0  -row 12 -columnspan 5 -sticky  w/);	

$entry =$mw1->Label(-font => '{Helvetica} 20', -width =>80, -textvariable => \$string2)->grid(qw/ -column 0  -row 13 -columnspan 5 -sticky  w/);
our $canvas = $mw1->Canvas(-width => 2286, -height => 858)->grid(qw/ -row 0 -column 0 -columnspan 6 -sticky n/);
# Load the images
$photo[0] = $mw1->Photo(-file => $images[0]{image});
$display[0] = $canvas->createImage(0, 0, -image => $photo[0], -anchor => 'nw', -state => 'disabled' );

# Function to handle mouse motion
my ($prevX, $prevY);
$current_item = $display[0];  # Initially select the first item

$canvas->Tk::bind('<Button-1>', sub {
($prevX, $prevY) = ($Tk::event->x, $Tk::event->y);
#say "current ****** item is** $current_item";
$index=$current_item;
});
$canvas->Tk::bind('<B1-Motion>', sub {
    my ($x, $y) = ($Tk::event->x, $Tk::event->y);
    my $dx = $x - $prevX;
    my $dy = $y - $prevY;
    $canvas->move($current_item, $dx, $dy) if defined $current_item;
    ($prevX, $prevY) = ($x, $y);
});
# Function to nudge the focused image
sub nudge_image {
    my ($direction) = @_;
    my ($dx, $dy) = (0, 0);
    if ($direction eq 'up') {
        $dy = -1;
    } elsif ($direction eq 'down') {
        $dy = 1;
    } elsif ($direction eq 'left') {
        $dx = -1;
    } elsif ($direction eq 'right') {
        $dx = 1;
    }
    $canvas->move($current_item, $dx, $dy) if defined $current_item;
}

$listbox->bind('<Double-Button-1>', \&select_item);
#$listbox->bind('<Button-3>', \&show_images);
$mw1->bind('<Return>', \&show_images);  # Bind Enter key to select_item

$mw1->bind('<KeyPress-1>', sub {$current_item = 2;});
#say "current item is $current_item";
$mw1->bind('<KeyPress-2>', sub {$current_item = 3;});
$mw1->bind('<KeyPress-3>', sub {$current_item = 4;});
$mw1->bind('<KeyPress-4>', sub {$current_item = 5;});
$mw1->bind('<KeyPress-5>', sub {$current_item = 6;});
$mw1->bind('<KeyPress-6>', sub {$current_item = 7;});
# Bind arrow keys
$mw1->bind('<Up>', sub { nudge_image('up') });
$mw1->bind('<Down>', sub { nudge_image('down') });
$mw1->bind('<Left>', sub { nudge_image('left') });
$mw1->bind('<Right>', sub { nudge_image('right') });

sub get_position {
my ($item) = @_;
say "current_item is $current_item, item is $item";
    my @coords = $canvas->coords($item);
    return \@coords;
}

# Button to retrieve position
sub find_position{
my ($current_item,$place) = @_;
my $lev=$current_item-1;
 $filename = $images[$lev]{image} if defined $images[$lev]{image};
 print "Filename of the current item: $filename\n";
my $pos1 = get_position($display[$level]);
   my $pos1x=$pos1->[0];
   my $pos1y=$pos1->[1];
    print "Position of Image $lev: @$pos1\n";
say "level is $level";
my($image_width, $image_height) = imgsize($filename);
print "image_width= $image_width image height= $image_height\n";
my $cw= $canvas->width;
my $ch= $canvas->height;
my $centre_x= $pos1x -($cw/2) +($image_width/2);
my $centre_y= $pos1y -($ch/2) +($image_height/2);
print "centre_x = $centre_x \n"; 
print "centre_y = $centre_y \n";
if($place eq "start"){$images[$lev]{start_x}=$centre_x;}
if($place eq "end"){$images[$lev]{end_x}=$centre_x;}

}

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);
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 {
say "current_item is==========$current_item";
#say Dumper $current_item;
my $last_selected_file=$selected_file;
$chk=$level+1;
$string="select a file";
my $path="./";
$selection = $listbox->get('active');
if(!$scene_name){$scene_name=$selection}
if($selection){say "$selection  $scene_name";
$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;
        print "Selected file: $selected_file\n"; 

$string="selected file is $selected_file";
$string2="mouse or arrow keys to move / select level with number keys"; 
$listbox->selectionClear(0, 'end');
if( $last_selected_file ne $selected_file){
$level=int($level);
$current_item=$level+1;
$canvas->addtag('current', 'withtag', $chk);
&show_images();
}
    }
}

sub show_images{
$level=int($level);
if($images[$level]{image}){
$images[$level]{image}="";
$photo[$level] = "";
$canvas->itemconfigure($display[$level], -image => $photo[$level]);
$canvas->delete('current');
}
say "current item= $current_item level= $level,";
$current_item=$level+1;
$images[$level]{image}=$selected_file;
$photo[$level] = $mw1->Photo(-file => $images[$level]{image});
$display[$level] = $canvas->createImage(0, 100, -image => $photo[$level], -anchor => 'nw');
$chk=$level+1;
$canvas->addtag('current', 'withtag', $chk);
$canvas->update;
say "here show_images level is $level";
}

sub multi{
say "current level is ".$level;
if (!$images[1]{start_x}||!$images[1]{end_x}){$string="need start and stop level 1";return();}
$dist[1] = abs($images[1]{start_x}-$images[1]{end_x});
$string="distances:     $dist[1]";
$string2="start is $images[$level]{start_x}: ends:";
my $layer_end;
my $frac=1/$layers;
for (my $i=1;$i<=$layers;$i++){
$dist[$i]= int((1-$frac*$i)*$dist[1]);
if ($images[1]{start_x}>$images[1]{end_x}){
$images[$i+1]{start_x}//=$images[1]{start_x};	
$layer_end=$images[$i+1]{start_x}-$dist[$i];
$images[$i+1]{end_x}=$layer_end;
}
else{
$images[$i+1]{start_x}//=$images[1]{start_x};
$layer_end=$images[1]{start_x}+$dist[$i];
$images[$i+1]{end_x}=$layer_end;
}
$string=join ' ',$string,$dist[$i];
$string2=join ' ',$string2,$layer_end;
$mw1->update;
}
print $string."\n";	
}
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 search_dir{
opendir(my $dh, ".") or die "Could not open directory: $!";
my @files = grep { -d $_ }readdir($dh);
closedir($dh);

@files = grep { !/^\.\.?$/ } @files;
foreach my $file (@files) {
    $listbox->insert('end', $file);
}


$selection = $listbox->get('active');
say $selection;
$listbox->bind('<Double-Button-1>', sub {
    $index = $listbox->curselection;
    if ($index) {
        $scene_name= $listbox->get($index);
        #$list_window->destroy;
        $listbox->selectionClear(0, 'end');
        @files="";
        return;
        }  
}
);
}
MainLoop;
#}
#1;
















