#!/usr/bin/perl
use strict;
use warnings;
use strict;
use warnings;
use Tk;
use File::Spec;
#use File::Copy::Recursive qw(dircopy);
use File::Copy;
use Image::Size;
use Image::Imlib2;
use File::Basename;
use Image::ExifTool;
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 ($image_width, $image_height);
my @files;
my @image_list;
my $size_x;
my $text;
my $dir;
my $new_name="new_name";
my ($new_crop_x,$new_crop_y,$new_crop_w,$new_crop_h,$new_size_w,$new_size_h,$degrees)=(100,100,100,100,100,100,100);
my $mw7 = MainWindow->new;
$mw7->title("CHANGE ALL IMAGES IN A DIRECTORY");
#$mw7->geometry("1100x860"); 
$mw7->geometry("1100x860+1100+500");
my $frame = $mw7->Frame()->grid(qw/ -row 0 -column 0  -sticky w/); 
my $frame3 = $mw7->Frame()->grid(qw/ -row 0 -column 2  -sticky w/); 
my $frame2=$mw7->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 =>5)->grid(qw/ -row 0 -column 0  -sticky w/); 
$listbox->bind('<Double-Button-1>', \&select_item);
my $button = $frame3->Button(-font => '{Helvetica} 15', -text => 'resize to width', -justify =>'left', -width=>12, -command => sub{&resize()})->grid(qw/ -row 0 -column 0 -sticky w/);
my $entry =$frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_size_w, -width=>5)->grid(qw/ -row 0 -column 1 -sticky w/);
#$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_size_h, -width=>5)->grid(qw/ -row 0 -column 2 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'rotate degrees', -justify =>'left', -width=>12, -command => sub{&rotate_all()})->grid(qw/ -row 2 -column 0 -sticky n/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$degrees, -width=>5)->grid(qw/ -row 2 -column 1 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => '-10', -justify =>'left', -width=>3, -command => sub{$degrees-=10;&circle;})->grid(qw/ -row 2 -column 2 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => '-1', -justify =>'left', -width=>3, -command => sub{$degrees-=1;&circle;})->grid(qw/ -row 2 -column 3 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => '+10', -justify =>'left', -width=>3, -command => sub{$degrees+=10;&circle;})->grid(qw/ -row 2 -column 4 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => '+1', -justify =>'left', -width=>3, -command => sub{$degrees+=1;&circle;})->grid(qw/ -row 2 -column 5 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'mirror', -justify =>'left', -width=>12, -command => sub{&mirror()})->grid(qw/ -row 4 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'flip diagonal', -justify =>'left', -width=>12, -command => sub{&flip_diagonal()})->grid(qw/ -row 6 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'crop x,y,w,h', -justify =>'left', -width=>12, -command => sub{&crop()})->grid(qw/ -row 8 -column 0 -sticky w/);
 $entry =$frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_crop_x, -width=>5)->grid(qw/ -row 8 -column 1 -sticky w/);
 $entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_crop_y, -width=>5)->grid(qw/ -row 8 -column 2 -sticky w/);
 $entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_crop_w, -width=>5)->grid(qw/ -row 8 -column 3 -sticky w/);
 $entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$new_crop_h, -width=>5)->grid(qw/ -row 8 -column 4 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => '00n-numbering', -justify =>'left', -width=>12, -command => sub{&renumber()})->grid(qw/ -row 10 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -justify =>'center', -textvariable => \$new_name, -width=>24)->grid(qw/ -row 10 -column 1 -columnspan 5 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'reverse numbers', -justify =>'left', -width=>12, -command => sub{&reverse()})->grid(qw/ -row 12 -column 0 -sticky w/);
#$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'randomize list', -justify =>'left', -width=>12, -command => sub{&randomize()})->grid(qw/ -row 14 -column 0 -sticky w/);
#$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'change_colour', -justify =>'left', -width=>10, -command => sub{&change_colour()})->grid(qw/ -row 16 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'remove exif data', -justify =>'left', -width=>12, -command => sub{&remove_exif()})->grid(qw/ -row 14 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'add transparency', -justify =>'left', -width=>12, -command => sub{&make_png()})->grid(qw/ -row 16 -column 0 -sticky w/);
$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'EXIT', -justify =>'left', -width=>12, -command => sub{$mw7->destroy()})->grid(qw/ -row 18 -column 0 -sticky w/);
$button = $mw7->Button(-font => '{Helvetica} 15', -text => 'UP', -width=>4, -command => \&go_up)->grid(qw/ -row 10 -column 0 -sticky w/); 

&refresh_listbox;
sub circle{
if($degrees>359){$degrees=0}if($degrees<0){$degrees=359}
}


MainLoop;
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;
    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);
        
         #&get_size();
        }
    }
}

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);
# get_size makes the @files array
 &get_size();$listbox2->insert('end', $text);
   } elsif (-f $path) {
        $selected_file = $path;
    }
    
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();
}

sub make_png{
&check_dir("transparent_");
#$text="add transparency";
$listbox2->insert('end', $text);
my $image;
#$image->image_set_format("png");
for(my$i=0;$i<=$#files;$i++){
my $type = `file $files[$i]`;
if ($type =~ /JPG/i || $type =~ /JPEG/i) {
my $file="$selected_dir/$files[$i]";
say $file;
my ($file2,$directories,$suffix) = fileparse($files[$i], qr/\.[^.]*$/); 
$image=Image::Imlib2->load($file);
$image->image_set_format("png");
$image->has_alpha(1);
$image->save("./transparent_/$selected_dir/$file2.png");
}
}
$text="done";
$listbox2->insert('end', $text); 
$image=undef;
}	








sub get_size{
$text="";
#if ($selected_dir){
opendir(my $dh, $selected_dir) or die "Could not open directory: $!";
@files = readdir($dh);
closedir($dh);
@files = grep { !/^\.\.?$/ } @files;
@files= sort numerically @files;
my $file="$selected_dir/$files[0]";	
say $file;
#my $file="$files[0]";
if ($file =~ /\.png$/i || $file =~ /\.jpg/i){
my ($image_width, $image_height) =imgsize($file);
$text="First file w= $image_width h= $image_height";
#$listbox2->insert('end', $text);	
}
#}

return;
	}
	
sub rotate_all{
&check_dir("rotated_");
$listbox2->insert('end', $text);
say " selected directory =  $selected_dir";
say "turn is $degrees  degrees";
my $image = Image::Imlib2->new();
my $rotated_image= Image::Imlib2->new();
for(my$i=0;$i<=$#files;$i++){
my $type = `file $files[$i]`;
if ($type =~ /JPEG/i || $type =~ /PNG/i) {
my $file="$selected_dir/$files[$i]";
say $file;
$image=Image::Imlib2->load($file);
$rotated_image =$image->create_rotated_image($degrees / 360 * 3.141519*2);;
$rotated_image->save("./rotated_/$selected_dir/rot_$files[$i]");
}
}
$text="done";
$listbox2->insert('end', $text); 
$rotated_image=undef;
$image=undef;
}


sub mirror{
&check_dir("mirrored_");
$listbox2->insert('end', $text);
my $image = Image::Imlib2->new();
my $mirrored_image = Image::Imlib2->new();
for(my$i=0;$i<=$#files;$i++){
my $type = `file $files[$i]`;
if ($type =~ /JPEG/i || $type =~ /PNG/i) {
my $file="$selected_dir/$files[$i]";
say $file;
$image=Image::Imlib2->load($file);
$mirrored_image=$image->flip_horizontal ();
$mirrored_image->save("./mirrored_/$selected_dir/mir_$files[$i]");
}
 }
$text="done";
$listbox2->insert('end', $text); 
$mirrored_image=undef;
$image=undef;
  }

sub resize{
&check_dir("resized_");
$listbox2->insert('end', $text);
my $image = Image::Imlib2->new();
my $resized_image = Image::Imlib2->new();
for(my$i=0;$i<=$#files;$i++){
my $type = `file $files[$i]`;
if ($type =~ /JPEG/i || $type =~ /PNG/i) {
my $file="$selected_dir/$files[$i]";
say $file;
$image=Image::Imlib2->load($file);
$resized_image=$image->create_scaled_image($new_size_w,0);
$resized_image->save("./resized_/$selected_dir/rez_$files[$i]");
}
}
$text="done";
$listbox2->insert('end', $text); 
$resized_image=undef;
$image=undef;
}

sub flip_diagonal{
&check_dir("flipped_");
$listbox2->insert('end', $text);
my $image = Image::Imlib2->new();
my $flipped_image = Image::Imlib2->new();
for(my$i=0;$i<=$#files;$i++){
my $type = `file $files[$i]`;
if ($type =~ /JPEG/i || $type =~ /PNG/i) {
my $file="$selected_dir/$files[$i]";
say $file;
$image=Image::Imlib2->load($file);
$flipped_image=$image->flip_diagonal();
$flipped_image->save("./flipped_/$selected_dir/flip_$files[$i]");
}
}
$text="done";
$listbox2->insert('end', $text); 
$flipped_image=undef;
$image=undef;
}

sub crop{
&check_dir("cropped_");
$listbox2->insert('end', $text);
my $image = Image::Imlib2->new();
my $cropped_image = Image::Imlib2->new();
for(my$i=0;$i<=$#files;$i++){
my $type = `file $files[$i]`;
if ($type =~ /JPEG/i || $type =~ /PNG/i) {
my $file="$selected_dir/$files[$i]";
say $file;
$image=Image::Imlib2->load($file);
$cropped_image = $image->crop($new_crop_x, $new_crop_y, $new_crop_w, $new_crop_h);;
$cropped_image->save("./cropped_/$selected_dir/crop_$files[$i]");
}
}
$text="done";
$listbox2->insert('end', $text); 
$cropped_image=undef;
$image=undef;
}

sub reverse{
&check_dir("reversed_");
my ($file,$directories,$suffix) = fileparse($files[0], qr/\.[^.]*$/);
$listbox2->insert('end', $text);
#@files= sort numerically @files;
my $ct=$#files;
for(my $i=0;$i<=$#files;$i++){
my $filename = sprintf("$selected_dir%03d$suffix", $ct);		
copy "./$selected_dir/$files[$i]","reversed_/$selected_dir/rev_$filename";	
$ct--;	
	}
}

sub renumber{
&check_dir("renumbered_");
#@files= sort numerically @files;
my $counter = 1;
my ($file,$directories,$suffix) = fileparse($files[0], qr/\.[^.]*$/);
foreach my $file (@files) {
       my $number = $counter++;
       my $new_name = sprintf("$new_name%04d$suffix", $number);
move("$selected_dir/$file", "$selected_dir/$new_name") or die "Failed to rename $file to $new_name: $!";
}
}


sub check_dir{
my $name=$_[0];
unless (-d "./$name") {mkdir "./$name";$text="made directory $name";}
else {$text= "$name directory exists"}
if (! -d "./$name/$selected_dir"){mkdir "./$name/$selected_dir";$text="made directory $name/$selected_dir";}	
return;
}


sub numerically {
    my ($a_num) = $a =~ /(\d+)/;
    my ($b_num) = $b =~ /(\d+)/;
$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 remove_exif{
my $orientation=3;
say "remove exif here";	
if(!$selected_dir){return}
#my $exifTool = new Image::ExifTool;
opendir(my $dh, $selected_dir) or die "Can't open $dir: $!";
my @files = grep { !/^\.\.?$/ } readdir($dh);
closedir($dh);
$listbox2->insert('end', @files);
foreach my $file (@files) {
my $exiftool = Image::ExifTool->new;
if ($file =~ /\.png$/i || $file =~ /\.jpg$/i){


say $file;
$exiftool->ExtractInfo("$selected_dir/$file");
#$orientation = $exifTool->GetValue('Orientation');
#say $orientation;
$exiftool->SetNewValue('*');
#$exiftool->SetNewValuesFromFile($file);
$exiftool->WriteInfo("$selected_dir/$file");
$exiftool=undef;
}
}
	}	
	
	
	
	
	
	
	
