package SCSite::PageSet;

use IO::All;
use Text::MultiMarkdown 'markdown';
use HTML::Zoom;
use Sub::Quote;
use Syntax::Keyword::Gather;
use SCSite::Page;
use Moo;
use Try::Tiny;

has top_dir => (is => 'ro', lazy => 1, builder => 'base_dir');
has base_dir => (is => 'ro', required => 1);
has max_depth => (is => 'ro', default => quote_sub q{ 0 });
has min_depth => (is => 'ro', default => quote_sub q{ 1 });

has rel_path => (is => 'lazy');

sub _build_rel_path {
  my ($self) = @_;
  io->dir('/')
    ->catdir(File::Spec->abs2rel($self->base_dir->name, $self->top_dir->name))
}

sub get {
  my ($self, $spec) = @_;
  $spec->{path} or die "path is required to get";
  my ($dir, $file) = $spec->{path} =~ m{^(?:(.*)/)?([^/]+)$};
  my $type;
  my @poss = io->dir($self->base_dir)->${\sub {
    my $io = shift;
    defined($dir) ? $io->catdir($dir) : $io
  }}->filter(sub {
        $_->filename =~ /^\Q${file}\E${\$self->_types_re}$/ and $type = $1
      })
    ->${\sub { -e "$_[0]" ? $_[0]->all_files : () }};
  die "multiple files found for ${\$spec->{path}}:\n".join "\n", @poss
    if @poss > 1;
  return undef unless @poss;
  $self->_inflate(
    $type, $self->rel_path->catdir($spec->{path}), $poss[0]->all
  );
}

sub _inflate {
  my ($self, $type, $path, $data) = @_;
  try { $self->${\"_inflate_${type}"}($path, $data) }
  catch {
    die "Error inflating ${path} as ${type}: $_\n\nData was: ${data}";
  }
}

sub map {
  my ($self, $mapper) = @_;
  [ map $mapper->($_), $self->flatten ]
}

sub _depth_under_base {
  my ($self, $path) = @_;
  File::Spec->splitdir(File::Spec->abs2rel($path, $self->base_dir->name))
}

sub flatten {
  my ($self) = @_;
  return unless (my $base = $self->base_dir)->exists;
  my %seen;
  my $slash = io->dir('/');
  my $min = $self->min_depth;
  map {
    my ($path, $type) = $_->name =~ /^(.*)${\$self->_types_re}$/;
    $self->_inflate(
      $type,
      $slash->catdir(File::Spec->abs2rel($path, $self->top_dir->name)),
      $_->all
    );
  } map {
    $_->filter(sub { $_->filename =~ /${\$self->_types_re}$/ })
      ->all_files($self->max_depth - ($min-1))
  } map
      $min > 1
        ? do {
            # can't use ->all_dirs($min-1) since we only want the final level
            my @x = ($_); @x = map $_->all_dirs, @x for 1..$min-1; @x
          }
        : $_,
      $base;
}

sub latest {
  my ($self, $max) = @_;
  require SCSite::LatestPageSet;
  SCSite::LatestPageSet->new(
    parent => $self,
    max_entries => $max,
  );
}

sub _new_page {
  SCSite::Page->new({ path => $_[1], page_set => $_[0], %{$_[2]} })
}

sub _types_re { qw/\.(html|md)/ }

sub _inflate_html {
  my ($self, $path, $html) = @_;
  $self->_new_page($path, $self->_extract_from_html($html));
}

sub _extract_from_html {
  my ($self, $html) = @_;
  HTML::Zoom->from_html($html)
    ->select('title')->collect_content({ into => \my @title })
    ->select('meta[name=subtitle]')->collect({ into => \my @subtitle })
    ->select('meta[name=description]')->collect({ into => \my @description })
    ->select('meta[name=keywords]')->collect({ into => \my @keywords })
    ->select('meta[name=created]')->collect({ into => \my @created })
    ->select('body')->collect_content({ into => \my @body })
    ->run;
  +{
    title => $title[0]->{raw}||'',
    subtitle => $subtitle[0]->{attrs}{content}||'',
    description => $description[0]->{attrs}{content}||'',
    keywords => $keywords[0]->{attrs}{content}||'',
    created => $created[0]->{attrs}{content}||'',
    body => HTML::Zoom->from_events(\@body)->to_html||'',
  }
}

sub _inflate_md {
  my ($self, $path, $md) = @_;
  $self->_new_page($path, $self->_extract_from_md($md));
}

sub _extract_from_md {
  my ($self, $md) = @_;
  $self->_extract_from_html(markdown($md, { document_format => 'complete' }));
}

1;
