package List::Index;

use 5.010;
use strict;
use warnings;

use Exporter 'import';

our $VERSION = '1.02';
our @EXPORT_OK = qw(rangematch);

sub new {
	my ($class, $options) = @_;
	$options ||= {};
	bless $options, $class;
}

sub ranges {
	my $self = shift;
	my @rows = sort map { s/[^a-z]/./g; $_ } @{ shift() };
	my $options = shift || {};
	$options->{$_} //= $self->{$_} for keys %$self;

	my $pagesize = $options->{pagesize} || 50;
	my $context  = $options->{context } // 1 + ($pagesize >> 4);
	my $length   = $options->{length  } || 4;
	my $pages    = $options->{pages   } || 1 + int $#rows / $pagesize;

	$pagesize = $pages >= $#rows ? 1 : @rows / $pages;
	my $lookbehind = -$context;
	my $lookahead  =  $context;

	my @links = ('');
	for (my $offset = $pagesize + .5; $offset < @rows; $offset += $pagesize) {
		my $link = substr $rows[$offset], 0, $length;
		if ($context) {
			my $penalty = 0;
			# take a value slightly before the current offset
			if ((my $before = $offset + $lookbehind) > 0) {
				# see how much of it matches the current link
				my $trim = 1;
				for my $match (split //, $rows[$before - 1]) {
					scalar $link =~ /\G\Q$match/g or last;
					$trim++;
				}
				# truncate link upto where the earlier value starts to differ
				if ($trim < length $link) {
					substr($link, $trim) = '';
					for (reverse $before .. $offset) {
						$rows[$offset - $penalty] =~ /^\Q$link/ or last;
						$penalty++;
					}
				}
			}

			$lookbehind = -$context;

			# take a value after the current offset
			if ((my $after = $offset + $lookahead) < $#rows) {
				# see how much of it matches the current link
				my $trim = 1;
				for my $match (split //, $rows[$after]) {
					scalar $link =~ /\G\Q$match/g or last;
					$trim++;
				}
				# use this link if it's shorter
				if ($trim < length $link) {
					$link = substr $rows[$after], 0, $trim;
					# advance lookbehind offset on the next page
					$penalty = 0;
					for ($offset .. $after) {
						last if $rows[$_] =~ /^\Q$link/;
						$lookbehind++;
					}
				}
			}

			$lookahead = $context - $penalty;
		}

		push @links, $link unless $links[-1] eq $link;
	}

	# add range end to each link
	for my $i (0 .. $#links - 1) {
		# end at start of next value with the last character decremented
		my $next = $links[$i + 1];
		$next =~ s{(.)$}{ $1 le 'a' ? '.' : chr( ord($1) - 1 ) }e;
		# amend range if it's ahead
		$links[$i] .= '-'.$next unless $next eq $links[$i];
	}
	# final value takes the rest
	$links[-1] .= '-';

	return \@links;
}

sub rangematch {
	my ($link) = @_;
	my ($s1, $s2) = $link =~ /([^-]*) - ([^-]*)/x
		or return qr/^\Q$link/i;
	$s1 =~ s/\.$//;
	my @allow;

	if (length $s1) {
		if (length $s2) {
			$s1 le $s2 or $s1 =~ /^\Q$s2/ or return undef;
		}

		my $prefix = '';
		my $char;
		for my $i (0 .. length($s1) - 1) {
			my $lasti = $i == length($s1) - 1;
			$char = substr $s1, $i, 1;
			my $next = $char;
			# do not include prefix character in final range
			$next = chr( ord($char) + 1 ) unless $lasti;

			my $last = 'z';
			next if $next gt $last;
			if (length $s2 > $i) {
				if ($s2 =~ /^\Q$prefix/) {
					$last = substr $s2, $i, 1;
					next if $char eq $last;
					$last = chr( ord($last) - (length $s2 > 1) );
					next if $next gt $last;
				}
			}

			if ($char eq '.') {
				if ($last eq 'z') {
#					push @allow, $prefix if $i and $lasti;
#					next;
				}
#				if ($last eq 'z') {
#					push @allow, $prefix if $i and $lasti;
#					next;
#				}
				$next = 'a';
			}

			push @allow, $prefix."[$next-$last]";
		}
		continue {
			$prefix .= $char eq '.' ? '[^a-z]' : $char;
		}
	}

	if (length $s2) {
		my $prefix = '';
		my $char;
		for my $i (0 .. length($s2) - 1) {
			$char = substr $s2, $i, 1;
			my $last = 'z';
			if (length $s1 > $i) {
				my $c1 = substr $s1, $i, 1;
				if ($s1 =~ /^\Q$prefix/) {
					next if $c1 le $char;
				}
			}

			if ($char eq '.') {
				next if $i < length($s2) - 1;
			}

			push @allow, $prefix.'(?!['.($char eq '.' ? 'a' : $char)."-$last])"
				if $i or $s1 eq '';
		}
		continue {
			$prefix .= $char eq '.' ? '[^a-z]' : $char;
		}

		push @allow, $prefix
			if $s2 =~ /^\Q$prefix/ and $s1 le $s2
			and not (length $s2 == 1 && length $s1 >= length $s2 && $s1 ne $s2);
	}

	my $match = sprintf @allow <= 1 ? '%s' : '(?:%s)', join('|', @allow);
	return qr/^$match/i;
}

1;

__END__

=head1 NAME

List::Index - Find and apply prefix ranges to paginate keywords

=head1 SYNOPSIS

	use List::Index;
	my $index = List::Index->new({ pagesize => 50 });
	my @pages = $index->ranges(\@values);
	say "<a href='?q=$_'>$_</a>" for @pages;

	use List::Index 'rangematch';
	my $limit = rangematch('b-bmq');  # ge 'b' && le 'bmq'
	@request = grep { $limit } @values;

=head1 DESCRIPTION

TODO

=head1 SEE ALSO

L<List::Maker|List::Maker> for complex ranges of numeric lists.

=head1 AUTHOR

Mischa POSLAWSKY <perl@shiar.org>

=head1 LICENSE

Copyright. All rights reserved.

