#!/usr/bin/perl
# vim:ft=perl:et:
our $APP     = 'rel';
our $VERSION = '2.24';
use strict;
use Parse::Flexget qw(flexparse);
use File::PatternMatch;
use File::Media::Sort;
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;

$Data::Dumper::Terse     = 1;
$Data::Dumper::Indent    = 1;
$Data::Dumper::Useqq     = 1;
$Data::Dumper::Deparse   = 1;
$Data::Dumper::Quotekeys = 0;
$Data::Dumper::Sortkeys  = 1;


our $style = 256;
our $opt_no_wanted = 1024;
GetOptions(
  'color'    => sub { $style = 256; },
  'dzen'     => sub { $style = 'dzen'; },
  'plain'    => sub { $style = 'none'; },
  'html'     => sub { $style = 'html'; },
  'number:i' => \$opt_no_wanted,
  'help'     => sub { pod2usage(verbose => 1); },
);


my $l = shift // "$ENV{FLEXGET_LOG}" // "$ENV{HOME}/.flexget/flexget.log";

open(my $fh, '<', $l) or print STDERR "No log found today.\n" and exit 1;
my @r = <$fh>;
close($l);

my $rel = patternmatch($style, flexparse(@r));

talk($rel, $opt_no_wanted);


sub talk {
  my $h = shift;
  my $no_wanted = shift;
  return if !$h;


  my $output = undef;
  my $next   = 0;

  my(undef,undef,undef,$mday,$mon,$year) = localtime(time);
  $year += 1900;
  $mon  += 1;
  printf("%55s \e[1m\e[4m%d-%02d-%02d\e[0m\n", 'Released',$year, $mon, $mday)
    unless($style eq 'dzen' or $style eq 'none');

  my $i = 0;
  for my $n(sort{ $a <=> $b } keys(%{$h})) {
    return(0) if($i == $no_wanted);
    for my $rel(keys(%{$h->{$n}})) {
      $output = $rel;
      if($style == 256) {
        printf("%s\e[38;5;236m▕\e[38;5;247m|\e[38;5;236m▏\e[0m%s\n",
          $output,$h->{$n}{$rel}, $output
        );
      }
      elsif($style eq 'dzen') {
        printf("%s^fg(#484848):^fg() %s^fg()\n",
          $h->{$n}{$rel}, $output,
        );
      }
      else {
        printf("%s %s\n",
          $output, $h->{$n}{$rel},
        );
      }
    }
    $i++;
  }
}


=pod

=head1 NAME

  rel

=head1 DESCRIPTION

=head1 OPTIONS

        --256     extended color output
  -d,   --dzen    dzen output
  -p,   --plain   normal output
  -n,   --number  return n records (most recent first)

  -h,   --help    show the help and exit

=head1 AUTHOR

Written by Magnus Woldrich

=cut
