#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use feature "say";
use File::Spec;
use POSIX ":sys_wait_h";

my @dir_stack = ('.');  # Stack to store directories navigated
my ($selected_file, $selected_dir, @contents, $print_dir, @files, $text, $dir, $blank, $img, $img_dir, $xy_file_dir);
my $key;
my $running_pid = 0;    # PID of currently running extractor (0 = none)

my $mw = MainWindow->new;
$mw->title("SELECT TO EXTRACT VIDEO"); 
$mw->geometry("1300x900+200+400");
my $font_large = ['Arial', 20];
my $font = '{Helvetica} 20';
my $label = $mw->Label(
    -font => $font,
    -text => "Use a video viewer like mpv to get rough time codes.\nA: for small and visual extract.(is too slow big files)\n B: for big video or extract frames.",
    -width => 45
)->grid(qw/ -row 0 -column 0 -columnspan 3 -sticky n/);

my $frame  = $mw->Frame()->grid(qw/ -row 2 -column 0  -sticky w/); 
my $frame2 = $mw->Frame()->grid(qw/ -row 4 -column 0 -sticky w/);
my $frame3 = $mw->Frame()->grid(qw/ -row 2 -column 1 -rowspan 4 -columnspan 2 -sticky w/);

my $button = $mw->Button(-font => $font, -text => 'GO UP', -justify => 'left', -width => 5, -command => sub { &GO_UP })->grid(qw/ -row 3 -column 0 -sticky w/);
$button = $mw->Button(-font => $font, -text => 'QUIT', -justify => 'left', -width => 5, -command => sub { kill_running(); $mw->destroy() })->grid(qw/ -row 5 -column 0 -sticky w/);

my $listbox = $frame->Scrolled('Listbox', -font => $font, -scrollbars => 'se', -width => 30)->grid(qw/ -row 0 -column 0 -sticky w/);
my $message_box = $frame2->Scrolled('Listbox', -font => $font, -scrollbars => 'se', -width => 30, -height => 6)->grid(qw/ -row 0 -column 1  -sticky w/); 
$listbox->bind('<Double-Button-1>', \&select_item);

$button = $frame3->Button(
    -font => $font,
    -text => 'A: video extract display',
    -justify => 'left',
    -width => 25,
    -command => sub { extract_small($selected_file) }
)->grid(qw/ -row 1 -column 0 -sticky nsew/);
my $entry = $frame3->Entry(-font => $font, -textvariable => \$selected_file, -width => 20)->grid(qw/ -row 1 -column 1  -sticky nsew/);

$button = $frame3->Button(
    -font => $font,
    -text => 'B: big video or frames extract',
    -justify => 'left',
    -width => 25,
    -command => sub { extract_big($selected_file) }
)->grid(qw/ -row 3 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$selected_file, -width => 20)->grid(qw/ -row 3 -column 1 -sticky nsew/);

&refresh_listbox;

# Periodically check if the child process has exited on its own
$mw->repeat(1000, \&reap_child);

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');
        } elsif ($item =~ /\.png$/i || $item =~ /\.jpg/i || $item =~ /\.webm$/i || $item =~ /\.avi/i || $item =~ /\.mp3/i || $item =~ /\.mp4/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;
        refresh_listbox();
        $selected_dir = $path;
        $text = "Selected directory: $selected_dir";
        $message_box->delete('0', 'end');
        $message_box->insert('0', $text);
    } elsif (-f $path) {
        $selected_file = $path;
        $text = "selected file = $selected_file";
        $message_box->insert('end', $text);
    }
    refresh_listbox();
}

sub GO_UP {
    pop @dir_stack if @dir_stack > 1;
    refresh_listbox();
}

# Kill any currently running extractor (and its process group) cleanly
sub kill_running {
    return unless $running_pid;
    if (kill 0, $running_pid) {          # still alive?
        say "Terminating previous extractor (PID $running_pid)...";
        # Kill the whole process group (negative PID)
        kill 'TERM', -$running_pid;
        # Short grace period
        my $waited = 0;
        while ($waited < 0.6 && kill(0, $running_pid)) {
            select(undef, undef, undef, 0.1);
            $waited += 0.1;
        }
        if (kill 0, $running_pid) {
            say "Force-killing process group of PID $running_pid";
            kill 'KILL', -$running_pid;
        }
    }
    waitpid($running_pid, WNOHANG);
    $running_pid = 0;
}

# Reap a child that exited by itself
sub reap_child {
    return unless $running_pid;
    my $reaped = waitpid($running_pid, WNOHANG);
    if ($reaped > 0 || $reaped == -1) {
        say "Extractor PID $running_pid finished.";
        $running_pid = 0;
    }
}

# Launch a command in the background and track its PID
sub launch {
    my ($cmd) = @_;
    kill_running();                      # stop whatever is currently running

    my $pid = fork();
    if (!defined $pid) {
        say "Fork failed: $!";
        return;
    }
    if ($pid == 0) {
        # Child process: start a new process group so we can kill everything later
        setpgrp(0, 0);
        exec($cmd) or die "exec failed: $!";
    }
    # Parent
    $running_pid = $pid;
    say "Started: $cmd  (PID $pid)";
    $message_box->insert('end', "Started PID $pid");
}

sub extract_small {
    my $file = shift;
    return unless defined $file && -f $file;
    say $file;
    launch("video-extract-small \"$file\"");
}

sub extract_big {
    my $file = shift;
    return unless defined $file && -f $file;
    say $file;
    launch("~/bin/video-extract-frames \"$file\"");
}

# Unused helpers kept for compatibility
sub numerically {
    my ($a_num) = $a =~ /(\d+)/;
    my ($b_num) = $b =~ /(\d+)/;
    $a_num //= 0;
    $b_num //= 0;
    return $a_num <=> $b_num;
}
