#!/usr/bin/env perl

use Kelp::Base -strict;
use Getopt::Long;
use Kelp::Generator;
use Path::Tiny;
use Pod::Usage;

my $path = '.';
my $verbose = 1;
my $force = 0;
my $type = 'kelp';
my $tabs = 0;
my $help = 0;

GetOptions(
    "path=s"   => \$path,
    "type=s"   => \$type,
    "verbose!" => \$verbose,
    "force!"   => \$force,
    "tabs!"    => \$tabs,
    "help"     => \$help
);

my $name = $ARGV[0];
my $generator = Kelp::Generator->new;

if ( !$name || $help ) {
    say 'Error - no application name.' unless $help;
    pod2usage(-verbose => 1, -exitval => 'NOEXIT');
    say 'Available application types:';
    say for map { ' ' x 4 . $_ } $generator->list_templates;
    exit ($help ? 0 : 1);
}

# Remove the slash at the end
$path =~ s{/$}{};
my $files = $generator->get_template($type, $name);

for my $filedata (@$files) {
    my ($filename, $contents) = @$filedata;

    # replace spaces with tabs
    # each 4 spaces will become a tab character
    # last 2 spaces will also become a tab due to rounding (+0.5)
    $contents =~ s{ ^ ((?: [ ]{4} | [ ]{2} )+) }{ "\t" x (length($1) / 4 + 0.5) }xmeg
        if $tabs;

    my $dir = $path . path("/$filename")->parent;
    my $file = path($path . '/' . $filename);

    if (!-d $dir) {
        _say("Creating folder: $dir");
        path($dir)->mkpath;
    }

    if ($file->is_dir) {
        say "$filename is a directory - manual action required. Skipping...";
        next;
    }

    if ($file->exists && !$force) {
        say "File $filename exists. Use --force to overwrite. Skipping...";
        next;
    }

    _say("Writing file: $filename");
    $file->spew($contents);
}

sub _say {
    my $what = shift;
    if ($verbose) {
        say $what;
    }
}

__END__

=pod

=head1 NAME

kelp-generator - Generate Kelp applications

=head1 SYNOPSIS

    kelp-generator [options] <application-name>

=head1 OPTIONS

=over 4

=item B<--path=s>

Path where to create the files

=item B<--type=s>

Type of application to create (default: kelp)

=item B<--(no)verbose>

Display more or less information

=item B<--force>

Force overwriting existing files

=item B<--tabs>

Use tabs for indentation instead of spaces

=item B<--help>

This help screen

=back

=head1 DESCRIPTION

B<This program> will generate a Kelp project from one of the registered
templates. C<< <application-name> >> will be used as the name of the package.

