#!/usr/bin/env perl

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

my $path = '.';
my $verbose = 1;
my $force = 0;
my $type = 'normal';
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] || do { $help = 1; '' };

if ( $help ) {
    my @usage = <DATA>;
    say @usage;
    say 'Available application types:';
    say for map { ' ' x 4 . $_ } Kelp::Generator->list_scenarios;
    exit;
}

# Remove the slash at the end
$path =~ s{/$}{};

# Get module path and name
my @parts = split( /::/, $name );
my $module_file = pop @parts;
my $module_path = join( '/', @parts );

my $files = Kelp::Generator->get_template($type, {
    name => $name,
    module_path => $module_path,
    module_file => $module_file,
});

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;
    }
}

__DATA__
Usage: Kelp [options] <name>

Options:
    --path=s        Path where to create the files
    --type=s        Type of application to create (default: normal)
    --types         List available application types
    --(no)verbose   Display information
    --force         Force overwriting existing files
    --tabs          Use tabs for indentation instead of spaces
    --help          This help screen
