#!/usr/bin/perl
use feature "say";
use Tk;
use File::Spec;
use Image::Size;
use File::Basename;
use Data::Dumper qw(Dumper);

my $source_directory;
my $width;
my $height;
my $save_name;
my $aspect;
my @dir_stack = ('.');  # Stack to store directories navigated
my $selected_file="";
my @contents;
my $print_dir;
my ($image_width, $image_height);
my @image_list;
my $size_x;
my $text;
my $dir;
my $frame_rate=100;
#my @palettes=qw(none trans16.png trans4.png blue.png green.png purple.png r102gb_trans3.png);
my @palettes=qw(none palette1.png palette2.png palette3.png palette4.png palette5.png);

my $palette_file=$palettes[0];
my $scale=100;
my $p=0;
my $saved_name="my_gif";

my $mw8 = MainWindow->new(-title => "MAKE A GIF FROM IMAGES IN DIRECTORY");
$mw8->geometry("800x1100+600+600");


my $entry = $mw8->Label(-font =>'{Helvetica} 20' , -text => "width of gif", -anchor => 'w', -width =>15)->grid(qw/ -row 6 -column 0 -sticky w/);
$entry = $mw8->Entry(-font => '{Helvetica} 20',  -textvariable => \$scale, -width =>12)->grid(qw/ -row 6 -column 1 -sticky w/);
my $button=$mw8->Button(-font =>'{Helvetica} 20', -text => "-", -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$scale=$scale-10;if ($scale<10){$scale=10}})->grid(qw/ -row 6 -column 0 -sticky e/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "+", -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$scale=$scale+10;if ($scale>=1000){$scale=1000}})->grid(qw/ -row 6 -column 2 -sticky w/);


$entry = $mw8->Label(-font =>'{Helvetica} 20' , -text => "palette file", -anchor => 'w', -width =>15)->grid(qw/ -row 8 -column 0 -sticky w/);
$entry = $mw8->Entry(-font => '{Helvetica} 20',  -width =>12, -textvariable => \$palette_file)->grid(qw/ -row 8 -column 1 -sticky w/);
$entry = $mw8->Label(-font =>'{Helvetica} 13', -text => "framerate is in milliseconds between frames", -anchor => 'w', -width =>50)->grid(qw/ -row 11 -column 0 -columnspan 2 -sticky w/);

$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "-", -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$p=$p-1;if ($p<0){$p=5};$palette_file=$palettes[$p];})->grid(qw/ -row 8 -column 0 -sticky e/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "+", -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$p=$p+1;if ($p>5){$p=0};$palette_file=$palettes[$p];})->grid(qw/ -row 8 -column 2 -sticky w/);


$entry = $mw8->Label(-font =>'{Helvetica} 20' , -text => "framerate", -anchor => 'w', -width =>15)->grid(qw/ -row 12 -column 0 -sticky w/);
$entry = $mw8->Entry(-font => '{Helvetica} 20', -width =>12, -textvariable => \$frame_rate)->grid(qw/ -row 12 -column 1 -sticky w/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "-", -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$frame_rate=$frame_rate-10;if ($frame_rate<=10){$frame_rate=10}})->grid(qw/ -row 12 -column 0 -sticky e/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "+", -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$frame_rate=$frame_rate+10;if ($frame_rate>=1000){$frame_rate=1000}})->grid(qw/ -row 12 -column 2 -sticky w/);

$entry = $mw8->Label(-font =>'{Helvetica} 20' , -text => "width of gif", -anchor => 'w', -width =>15)->grid(qw/ -row 13 -column 0 -sticky w/);
$entry = $mw8->Entry(-font => '{Helvetica} 20', -width =>12, -textvariable => \$width)->grid(qw/ -row 13 -column 1 -sticky w/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "X", -justify => 'left',  -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$width=undef;})->grid(qw/ -row 13 -column 2 -sticky w/);

$entry = $mw8->Label(-font =>'{Helvetica} 20' , -text => "height of gif", -anchor => 'w',  -width =>15,)->grid(qw/ -row 14 -column 0 -sticky w/); 
$entry = $mw8->Entry(-font => '{Helvetica} 20', -width =>12, -textvariable => \$height)->grid(qw/ -row 14 -column 1 -sticky w/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "X", -justify => 'left',  -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 2, -anchor => 'n', -command => sub {$height=undef;})->grid(qw/ -row 14 -column 2 -sticky w/);

$entry = $mw8->Label(-font =>'{Helvetica} 13' , -text => "no height or width keeps image aspect: ", -anchor => 'w', -width =>40)->grid(qw/ -row 15 -column 0 -columnspan 2 -sticky w/);

$entry = $mw8->Label(-font =>'{Helvetica} 20' , -text => "save name", -anchor => 'w',  -width =>15)->grid(qw/ -row 16 -column 0 -sticky w/); 
$entry = $mw8->Entry(-font => '{Helvetica} 20', -textvariable => \$save_name, -width =>12)->grid(qw/ -row 16 -column 1 -sticky w/);
$entry = $mw8->Label(-font =>'{Helvetica} 20' , -text => "directory", -anchor => 'w',  -width =>15)->grid(qw/ -row 17 -column 0 -sticky w/); 
$entry = $mw8->Entry(-font => '{Helvetica} 20', -width =>12, -textvariable => \$selected_file)->grid(qw/ -row 17 -column 1 -sticky w/);

$entry = $mw8->Label(-font =>'{Helvetica} 13' , -text => "select an image to get its size & aspect", -anchor => 'w', -width =>40)->grid(qw/ -row 18 -column 0 -columnspan 2 -sticky w/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "make gif", -justify => 'center',  -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 15, -anchor => 'n', -command => sub {&make_gif})->grid(qw/ -row 20 -column 0 -sticky w/);
$button=$mw8->Button(-font =>'{Helvetica} 20', -text => "SELECT", -justify => 'center',  -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -width => 12, -anchor => 'n', -command => sub {&select_images})->grid(qw/ -row 20 -column 1 -sticky w/);
$button=$mw8->Button(-font => '{Helvetica} 20', -width =>12, -text => "CLOSE", -justify => 'center', -relief =>'raised', -borderwidth => 2, -pady => 2, -padx  => 2, -command =>sub{$mw8->destroy;})->grid(qw/ -row 30 -column 1 -sticky w/);


$button = $mw8->Button(-font => '{Helvetica} 15', -text => 'UP', -width => 4, -command => \&go_up)->grid(qw/ -row 26 -column 0 -sticky w/); 
my $listbox = $mw8->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width=>30)->grid(qw/ -row 24 -column 0 -columnspan 2 -sticky w/); 
$listbox->bind('<Double-Button-1>', \&select_item);
$listbox->bind('<Return>', \&select_item);  # Bind Enter key to select_item
my $frame = $mw8->Frame()->grid(qw/ -row 28 -column 0 -columnspan 2 -sticky e/); 
my $listbox2 = $frame->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width=>30, -height=>5)->grid(qw/ -row 28 -column 0  -sticky w/); 
refresh_listbox();

sub select_images{
my ($file,$directories,$suffix) = fileparse($dir, qr/\.[^.]*$/);
if(!$save_name){$save_name="$file";
$save_name=join'.',$save_name,'gif';}
say $saved_name;
say $file;
say $directories;
say $suffix;

if(!$image_width){$selected_file="";return}
$aspect = $image_height/$image_width;
#our $scale= int($aspect*100);
if(!$width && !$height){
    $width=$image_width;$height=$image_height;}
elsif(!$height){
	$height=int($width*$aspect);}
elsif(!$width){
	$width=int($height/$aspect);}
say $image_width." ", $image_height." ".$aspect;
say "directory= $selected_file";	
	}
	
sub make_gif{
unless ($palette_file eq "none"){$palette_file="./palettes/$palette_file";}
#my $text2="ffmpeg -f image2 - framerate $frame_rate -i $save_name -vf scale= $width x $height $save_name";	
say $text;	
#sorts the file list into numerical padded with 00s	
say " selected file = $selected_file";
opendir(my $dh, $selected_file) or die "Cannot open directory $dir: $!";

my @file_list = readdir($dh);
closedir($dh);	
# Filter and sort the files
@file_list = grep { !/^\.\.?$/ } @file_list;
@file_list = sort {
   my ($anum) = $a =~ /(\d+)/;
   my ($bnum) = $b =~ /(\d+)/;
    $anum <=> $bnum;
} @file_list;

# Create a temporary file list for ffmpeg
my $dtext="duration 00:00:00.$frame_rate";
say $dtext;
my $filelist = 'filelist.txt';
open(my $fh, '>', $filelist) or die "Cannot open filelist: $!";
foreach my $file (@file_list) {
    print $fh "file '$selected_file/$file'\n";
	print $fh "$dtext \n";
}
close($fh);	
say " text  $text";
#make a pallete. don't delete this
say "palette file is $palette_file";
if($palette_file eq "none"){
system("ffmpeg -y -i $text -vf palettegen palette.png ");
say "*************";
$palette_file="palette.png";
}
$listbox2->insert('end',"$palette_file");
# -pix_fmt yuvj422p
# shell_exec($tmp = "$ffmpeg -i $video_url -pix_fmt yuvj422p -deinterlace -an -ss $interval -f mjpeg -t 1 -r 1 -y -s $size $image 2>&1");
my $ffmpeg_command = "ffmpeg -y -f concat -safe 0 -i $filelist -i $palette_file -filter_complex \"[0:v]scale=$scale:-1,setsar=1[vid];[vid][1:v]paletteuse\"  $save_name";
system($ffmpeg_command);

# Clean up temporary file
#unlink $filelist;
$listbox2->insert('end',"done");
say "done";
exit;	
	}
	
sub refresh_listbox {

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


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;
      }

#    ($image_width, $image_height) = imgsize("$text");
    say "w = $image_width, h = $image_height";
  $listbox2->insert(0, "$text,");
  $listbox2->insert('end', "w = $image_width, h = $image_height");
#push(@image_list,$text);
}

sub go_up {
   $selected_file="";
    pop @dir_stack if @dir_stack > 1;  # Pop the top directory from the stack if not already at the root
    refresh_listbox();
}
MainLoop;

