# Album Plugin:	org/specified_sort
# For info:	'album -plugin_info org/specified_sort'
# For usage:	'album -plugin_usage org/specified_sort'
use strict;

my $LICENSE = << 'LICENSE';
Copyright (c) 2005 Scott J. Bertin

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
LICENSE

my $DESCRIPTION = << 'DESCRIPTION';
Sort pics/dirs as specified in a file (default "album.order").

The file can list names or directives to override some or all
of the normal album sorting.

Unknown names are sorted in the default album order.

The following special 'names' are recognized:
    [:NOREVERSE:] Ignores the reverse_sort option for the current file.
    [:UNKNOWN:]   Placeholder for unknown values, overrides the
                  unknowns_first option.
    [:DIRSONLY:]  Only sort directories, not pics.
    [:PICSONLY:]  Only sort pics, not directories.

If both [:DIRSONLY:] and [:PICSONLY:] both appear in the file, no
special sorting is done.

The file is only checked for exact matches, patterns are not used. This is
intentional so that the order is unambiguous.

If an item appears twice in the file, the order of that item will depend on
the first occurence that is found when the search is made. This creates
interesting possibilities for ordering with and without the reverse_sort
option. If you put an item both first and last in the file, it will appear
first regardless of the reverse_sort option, assuming no unknowns, or an
[:UNKNOWNS:] line between the 2 occurrences.
DESCRIPTION

sub start_plugin {
  my ($opt) = @_;

  # Setup the options
  album::add_option(1, 'show_license', album::OPTION_BOOL, one_time=>1,
                    usage=>'Show the license for this plugin.');
  album::add_option(1, 'what_to_sort', album::OPTION_STR, default=>'both',
                    usage=>'What to sort (pics, dirs, both)');
  album::add_option(1, 'ignore_reverse', album::OPTION_BOOL,
                    usage=>'Ignore the reverse_sort option');
  album::add_option(1, 'unknowns_first', album::OPTION_BOOL,
                    usage=>'Sort unknown pics/dirs first? (default is last)');
  album::add_option(2, 'filename', album::OPTION_STR, default=>'album.order',
                    usage=>'Name of the file containing the sort order.');
  
  # Setup the hooks
  album::hook($opt, 'sort_dirs', \&do_sort);
  album::hook($opt, 'sort_pics', \&do_sort);

  return {
    author => 'Scott J. Bertin',
    href => 'mailto://scottbertin@yahoo.com',
    version => '1.0',
    description => $DESCRIPTION,
  };
}

sub find_index {
  my ($element,$array) = @_;
  
  return undef unless $array;
  
  for(my $i=0; $i<scalar(@$array); $i++) {
    return $i if @$array[$i] eq $element;
  }
  return undef;
}

sub sort_order {
  my ($opt,$data,$before,$after,$a,$b) = @_;

  my $a_before = find_index($a, $before);
  my $b_before = find_index($b, $before);
  if (defined $a_before) {
    if (defined $b_before) {
      return $a_before <=> $b_before;
    } else {
      return -1;
    }
  } elsif (defined $b_before) {
    return 1;
  }
  
  my $a_after = find_index($a, $after);
  my $b_after = find_index($b, $after);
  if (defined $a_after) {
    if (defined $b_after) {
      return $a_after <=> $b_after;
    } else {
      return 1;
    }
  } elsif (defined $b_after) {
    return -1;
  }
  
  return album::sort_order($opt, $data, $a, $b);
}

sub read_file {
  my ($f) = @_;
  return undef unless $f;
  return undef unless (-r $f);
  return undef unless (open(FILE,"<$f"));
  my @contents;
  while(<FILE>) {
    # Strip leading and trailing whitespace
    s/^\s+//; s/\s+$//;
    # Skip blank lines
    push(@contents,$_) unless length($_) == 0;
  }
  close FILE;
  return @contents;
}

sub do_sort {
  my ($opt, $data, $hookname, @list) = @_;
  
  show_license($opt) if album::option($opt, 'show_license');
  
  my $sort_type = lc album::option($opt, 'what_to_sort');
  
	my $me = album::curr_plugin($opt);
  album::usage("Unknown ${me}:what_to_sort option: $sort_type\n".
               "\tShould be pics, dirs, or both.")
    unless grep($sort_type eq $_, qw(pics dirs both));

  return undef if $hookname eq 'sort_dirs' && $sort_type eq 'pics';
  return undef if $hookname eq 'sort_pics' && $sort_type eq 'dirs';
  
  # Get the order for this album
  my $dir = $data->{paths}{dir};
  my $filename = album::option($opt, 'filename');
  my $slash = album::option($opt, 'slash');
  my @order = read_file($dir.$slash.$filename);
  
  return undef unless defined $order[0];
  
  # Check for limitations on what to sort
  my $dirsonly = find_index('[:DIRSONLY:]', \@order);
  my $picsonly = find_index('[:PICSONLY:]', \@order);
  
  return undef if $hookname eq 'sort_dirs' && defined $picsonly;
  return undef if $hookname eq 'sort_pics' && defined $dirsonly;
  
  # Remove [:DIRSONLY:] and [:PICSONLY:] from the order
  if(defined $dirsonly) {
    splice(@order, $dirsonly, 1);
  } elsif(defined $picsonly) {
    splice(@order, $picsonly, 1);
  }

  # Should the reverse flag be ignored for the specified order
  my $reverse = $opt->{reverse_sort};
  my $noreverse = find_index('[:NOREVERSE:]', \@order);
  if(defined $noreverse) {
    # Remove [:NOREVERSE:]
    splice(@order, $noreverse, 1);
  } elsif ($reverse && !album::option($opt, 'ignore_reverse')) {
    @order = reverse @order;
  }
  
  # Split the order into parts before and after unknown elements
  my $unknown = find_index('[:UNKNOWN:]', \@order);
  my $before;
  my $after;
  if(defined $unknown) {
    if($unknown > 0) {
      $before = [@order[0..$unknown-1]];
    }
    if($unknown < $#order) {
      $after = [@order[$unknown+1..$#order]];
    }
  } else {
    if($reverse xor album::option($opt, 'unknowns_first')) {
      $after = \@order;
    } else {
      $before = \@order;
    }
  }
  
print "PS LIST: @list\n";
  return sort { sort_order($opt, $data, $before, $after, $a, $b) } @list;
}

sub show_license {
  my ($opt) = @_;
  
	my $me = album::curr_plugin($opt);
  print "The following license applies ONLY to the ",
        "$me plugin, and should not be construed ",
        "to apply to album, or any other plugin.\n\n", $LICENSE;
  exit;
}

# Plugins always end with:
1;
