package Mojolicious::Plugin::Riotjs::Preprocessor;

=head1 NAME

Mojolicious::Plugin::Riotjs::Preprocessor - Preprocessor for Riot tag files

=head1 DESCRIPTION

L<Mojolicious::Plugin::Riotjs::Preprocessor> is a preprocessor for
L<riotjs|https://muut.com/riotjs/> C<.tag> files.

Riot is required for this module to work. You can install Riot on Ubuntu and
Debian using this command:

  $ sudo apt-get install npm
  $ npm install riot

=cut

use Mojo::Base 'Mojolicious::Plugin::AssetPack::Preprocessor';
use File::Basename 'dirname';
use File::Spec  ();
use File::Which ();

=head1 ATTRIBUTES

=head2 executable

  $path = $self->executable;

Holds the path to the "riot" executable. Default to just "riot".

=cut

has executable => sub {
  my $self = shift;
  my $local = File::Spec->catfile($self->cwd, 'node_modules', '.bin', 'riot');
  return $local if -e $local;
  return File::Which::which('riot') || 'riot';
};

has _compile_cmd => sub {
  return [
    File::Which::which('nodejs') || File::Which::which('node'),
    File::Spec->catfile(dirname(__FILE__), 'compile.js'),
  ];
};

=head1 METHODS

=head2 can_process

Returns true if L</executable> points to an actual file.

=cut

sub can_process { -f $_[0]->executable ? 1 : 0 }

=head2 process

This method use "riot" to process C<$text>.

See L<Mojolicious::Plugin::AssetPack::Preprocessor/process>.

=cut

sub process {
  my ($self, $assetpack, $text, $path) = @_;
  my $err = '';

  local $ENV{RIOT_COMPACT} = $assetpack->minify ? 1 : 0;
  $self->_run($self->_compile_cmd, $text, $text, \$err);
  $self->_make_js_error($err, $text) if length $err;
  $self;
}

sub _url {'https://muut.com/riotjs/'}

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2014, Jan Henning Thorsen

This program is free software, you can redistribute it and/or modify it under
the terms of the Artistic License version 2.0.

=head1 AUTHOR

Jan Henning Thorsen - C<jhthorsen@cpan.org>

=cut

1;
