#!/usr/bin/perl
use strict;
use warnings;
use strict;
use warnings;
use Tk;
#use File::Spec;
#use File::Basename;
#use Math::Trig;
use Math::Round;
use Image::Size qw/imgsize/;
use Image::Imlib2;
use Text::CSV_XS;
use feature "say";
use Data::Dumper qw(Dumper);
my @dir_stack = ('.');  # Stack to store directories navigated
my $selected_file;
my $selected_dir;
my @contents;
my $print_dir;
my $text;
my $dir;
my $frames=3;
my @temp;
my @dope;
my $base_img;
my $file;
my $bg="BLANK";
my $save_directory="MIXES";
my $canvas_width=400;
my $aspect=1;
my @mix_frames=qw(3 4 6 8);
my $num=0;
my $mw = MainWindow->new;
$mw->title("MAKE MIX FRAMES"); 
$mw->geometry("1100x860+1100+500");
my $frame = $mw->Frame()->grid(qw/ -row 2 -column 0  -sticky w/); 
my $frame3 = $mw->Frame()->grid(qw/ -row 2 -column 1  -sticky w/); 
my $frame2=$mw->Frame()->grid(qw/ -row 12 -column 0 -sticky w/);
my $listbox = $frame->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width=>30)->grid(qw/ -row 0 -column 0 -sticky w/);
my $listbox2 = $frame2->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width=>30, -height =>6)->grid(qw/ -row 0 -column 0  -sticky w/); 
$listbox->bind('<Double-Button-1>', \&select_item);
my $button = $frame->Button(-font => '{Helvetica} 15', -text => 'UP', -width=>4, -command => \&go_up)->grid(qw/ -row 10 -column 0 -sticky w/); 


my $label=$frame3->Label(-font => '{Helvetica} 20', -text => "double click whxy file to select.\nIf no background or BLANK(.png)\nbackground is size of overlay", -width=>26)->grid(qw/ -row 10 -column 0 -columnspan 4 -sticky e/);
my $entry =$frame3->Label(-font => '{Helvetica} 15', -text => " \n", -width=>20)->grid(qw/ -row 11 -column 0 -sticky w/);
$label=$frame3->Label(-font => '{Helvetica} 15', -text => "save images directory:", -width=>18, -justify => 'center')->grid(qw/ -row 12 -column 0 -sticky n/);
$entry =$frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$save_directory, -width=>10, -justify => "center")->grid(qw/ -row 12 -column 1 -sticky w/);
$entry =$frame3->Label(-font => '{Helvetica} 15', -text => 'mix frames', -width=>10, -justify => "center")->grid(qw/ -row 13 -column 0 -sticky n/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$frames, -width=>10, -justify => "center")->grid(qw/ -row 13 -column 1 -sticky w/);

#$entry =$frame3->Button(-font => '{Helvetica} 15', -text => '<-', -width=>1, -justify => "left", -command => sub{$num=$num-1;if($num<0){$num=3};$frames=$mix_frames[$num];})->grid(qw/ -row 13 -column 2 -sticky w/);
$entry =$frame3->Button(-font => '{Helvetica} 15', -text => '-->', -width=>4, -justify => "left", -command => sub{$num=$num+1;if($num>3){$num=0}$frames=$mix_frames[$num];})->grid(qw/ -row 13 -column 2 -sticky w/);


$entry =$frame3->Button(-font => '{Helvetica} 15', -text => 'background', -width=>12, -justify => "center", -command => sub{if(defined $selected_file){$bg=$selected_file;say $bg;}})->grid(qw/ -row 14 -column 0 -sticky w/);
$entry =$frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$bg, -width=>20, -justify => "left")->grid(qw/ -row 14 -column 1 -columnspan 3 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'image,whxy file', -justify =>'left', -width=>12, -command => sub{if(defined $selected_file){$file=$selected_file;say $file;}})->grid(qw/ -row 16 -column 0 -sticky w/);
$entry =$frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$file, -width=>20, -justify => "left")->grid(qw/ -row 16 -column 1 -columnspan 3 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'make mixes', -justify =>'center', -width=>12, -command => sub{&make_array()})->grid(qw/ -row 17 -column 0 -sticky w/);


$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'EXIT', -justify =>'left', -width=>12, -command => sub{$mw->destroy()})->grid(qw/ -row 20 -column 0 -sticky w/);


&refresh_listbox;
MainLoop;

sub numerically {
    my ($a_num) = $a =~ /(\d+)/;
    my ($b_num) = $b =~ /(\d+)/;
say "a $a_num b $b_num";
$a_num //= 0;  # Set $a_num to 0 if it's uninitialized
$b_num //= 0;  # Set $b_num to 0 if it's uninitialized
return $a_num <=> $b_num;
}

sub make_array{
say "here make array $bg";


&check_dir;
my $ct=0;
my $csv = Text::CSV_XS->new ();

open (my $fh , '<',"$file")or die"$!";		
while (my $line = <$fh>) {
      $csv->parse($line);
      my %values=$csv->fields();
 if(!defined $values{x} || !defined $values{y}){$text="! file does not have xy data !";$listbox2->insert('end', $text);return;}
 $temp[$ct]{x}=$values{x};
 $temp[$ct]{y}=$values{y};

 if(!defined $values{w}|| !defined $values{h}){$text="! file does not have wh data !";$listbox2->insert('end', $text);return;}
 $temp[$ct]{w}=$values{w};
 $temp[$ct]{h}=$values{h};

 if(!defined $values{image}){$text="! file does not have image data !";$listbox2->insert('end', $text);return;}
 $temp[$ct]{image}=$values{image};

 $ct++;
}	
@temp = grep { !/^\.{1,2}$/ } @temp;  # Remove "." and ".." entries



my $canvas_height=$canvas_width*$aspect;
#say "$img_width $img_height";

# change centers x y to top left 
for(my $i=0; $i<=$#temp;$i++){
$dope[$i]{x}=(($canvas_width-$temp[$i]{w})/2)+$temp[$i]{x};
$dope[$i]{y}=(($canvas_height-$temp[$i]{h})/2)+$temp[$i]{y};
$dope[$i]{image}=$temp[$i]{image};
	}
my $count=$#dope * $frames;
say "count = $count";
my ($img_width, $img_height) = imgsize($dope[0]{image});
say "width= $img_width height= $img_height"; 
if ($bg eq "BLANK"){
$base_img=Image::Imlib2->new_transparent($img_width,$img_height);
say "made bg same size as overlays";
}
elsif(defined $bg && -f $bg){

say "bg exists";
}
else{
say	"bg does not exist";return;
	}
for ( my $i=0;$i<=2;$i++){
for (my $n=0;$n<=$frames;$n++){
do_fade($dope[$i]{image},200);
do_fade($dope[$i+1]{image},125);

$base_img->save("test_mix_$i\_$n.png");	

	}
say $dope[$i]{image};	
	
	}
say "done";	

#$base_img = Image::Imlib2->load($bg);





}#end of make_array

#my $base_img = Image::Imlib2->load($bg);
#$base_img->will_blend(0);
#$base_img->has_alpha(0);

sub do_fade{
#($image_width,$image_height) =imgsize($file);
#my ($file,$directories,$suffix) = fileparse($files[$i], qr/\.[^.]*$/);	
my ($file,$f)=@_;
$base_img=Image::Imlib2->load($bg);	
$base_img->will_blend(0);
$base_img->has_alpha(0);


my $img=Image::Imlib2->load($file);
my $width = $img->width;
my $height = $img->height;
my $image = $img->create_transparent_image($f);
$image->will_blend(0);# need this to be (0)
$image->set_colour(0, 0, 0, 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==0 && $g==0 && $b==0){
        $image->draw_point($x, $y);
       }
           }
}
$image->will_blend(1);
$base_img->blend($image,1 , 0, 0, $width, $height, 0, 0, $width, $height);

return;
}

sub check_dir{
# makes directories to save the image files in
unless (-d "./$save_directory") {mkdir "./$save_directory"}
unless (-d "./$save_directory/images") {mkdir "./$save_directory/images";$text="made directory $save_directory/images";}	
$listbox2->insert('end', $text);
return;
}





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);
@contents = sort { lc($a) cmp lc($b) } @contents; #order array
    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 || $item =~ /\.list/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) {
        push @dir_stack, $path;  # Push selected directory to the stack
        refresh_listbox();
        $selected_dir=$path;
 $text="Selected directory: $selected_dir";
 $listbox2->delete('0', 'end');
 $listbox2->insert('0', $text);

   } elsif (-f $path) {
        $selected_file = $path;
        $text= "selected file = $selected_file";
        $listbox2->insert('end', $text);
    }
 if ($selected_file eq "./BLANK.png"){
	$selected_file="BLANK"; 
	 }   
refresh_listbox();
}

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