package App::SCS::Plugin::Generate::StaticServer;

use Module::Runtime qw(use_module);
use Web::Simple;

has dir => (is => 'ro', required => 1);

has app => (is => 'ro', required => 1);

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

sub _build__dir_handler {
  my ($self) = @_;
  use_module('Plack::App::File')->new(
    root => $self->dir
  );
}

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

sub _build__static_handler {
  my ($self) = @_;
  use_module('Plack::App::File')->new(
    root => $self->app->share_dir->catdir('static')
  );
}

sub dispatch_request {
  my ($self) = @_;
  sub (/**.*) {
    my $path = $_[1];
    return unless $path =~ s/\/-/\//;
    App::SCS::Web::redispatch_to("/static/${path}");
  },
  sub (/static/...) { $self->_static_handler },
  sub (/favicon + .ico) { $self->_static_handler },
  $self->_dir_handler
}

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

1;
