package SCSite::DevMode;

use Plack::App::File;
use Plack::Runner;
use Try::Tiny;
use Moo::Role;

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

sub _build__static_handler {
  my ($self) = @_;
  my $static_dir = $self->config->{static_dir};
  Plack::App::File->new(root => $static_dir);
}

around dispatch_request => sub {
  my ($orig, $self) = (shift, shift);
  no warnings::illegalproto;
  (
    sub (/**.*) {
      my ($self, $path) = @_;
      return unless $path =~ s/\/-/\//;
      SCSite::redispatch_to "/static/${path}";
    },
    sub (/static/...) { $self->_static_handler },
    sub (/favicon + .ico) { $self->_static_handler },
    $self->$orig(@_)
  )
};

sub _run_dev_server {
  my ($self, @args) = @_;
  my $r = Plack::Runner->new(server => 'Starman', app => $self->to_psgi_app);
  $r->parse_options(@args);
  $r->set_options(argv => \@args);
  $r->run;
}

sub _run_dev_checkall {
  my ($self) = @_;
  my $ps = $self->pages;
  foreach my $path ($ps->all_paths) {
    try {
      $ps->get({ path => $path });
      print "OK ${path}\n";
    } catch {
      print "ERROR ${path}\n";
      print "  $_";
    };
  }
}

1;
