#!/usr/bin/perl

use strict;
use warnings;
use utf8;
use File::Path qw/mkpath/;
use Getopt::Long;
use Pod::Usage;
use Text::Xslate;
use Data::Section::Simple qw(get_data_section);
use MIME::Base64;
use Kossy::Assets;

require Kossy;

GetOptions(
    'help' => \my $help,
) or pod2usage(0);
pod2usage(1) if $help;

sub _mkpath {
    my $d = shift;
    print "mkdir $d\n";
    mkpath $d;
}

my $module = shift @ARGV or pod2usage(0);
my @pkg  = split /::/, $module;
my $dist = join "-", @pkg;
my $path = join "/", @pkg;

my $tx = Text::Xslate->new(syntax => 'TTerse');

mkdir $dist or die $!;
chdir $dist or die $!;
_mkpath "lib/$path";
_mkpath "views";
_mkpath "public";
_mkpath "public/js";
_mkpath "public/css";
_mkpath "public/images";
_mkpath "t";

my $files = get_data_section();
my $args = {
    module => $module,
    path => $path,
    dist => $dist,
    myver => $Kossy::VERSION,
};
foreach my $fkey ( keys %{$files} ) {
    my $path = $tx->render_string($fkey, $args);
    my $content = $tx->render_string($files->{$fkey}, $args);
    print "writing $path\n";
    open(my $fh, '>', $path);
    print $fh $content
}

my $assets_reader = Data::Section::Simple->new('Kossy::Assets');
my $assets = $assets_reader->get_data_section;
foreach my $fkey ( keys %$assets ) {
    my $path = $fkey;
    my $content = $assets->{$path};
    if ( $path =~ m!\.b64$! ) {
        $path =~ s/\.b64$//g;
        $content = decode_base64($content);
    }
    print "writing $path\n";
    open(my $fh, '>', $path);
    print $fh $content;
}

=head1 SYNOPSIS

    % kossy-setup MyApp

=cut

1;
__DATA__
@@ lib/[% path %].pm
package [% module %];

use strict;
use warnings;
use utf8;

our $VERSION = 0.01;

1;

@@ lib/[% path %]/Web.pm
package [% module %]::Web;

use strict;
use warnings;
use utf8;
use Kossy;

filter 'set_title' => sub {
    my $app = shift;
    sub {
        my ( $self, $c )  = @_;
        $c->stash->{site_name} = __PACKAGE__;
        $app->($self,$c);
    }
};

get '/' => [qw/set_title/] => sub {
    my ( $self, $c )  = @_;
    $c->render('index.tx', { greeting => "Hello" });
};

get '/json' => sub {
    my ( $self, $c )  = @_;
    my $result = $c->req->validator([
        'q' => {
            default => 'Hello',
            rule => [
                [['CHOICE',qw/Hello Bye/],'Hello or Bye']
            ],
        }
    ]);
    $c->render_json({ greeting => $result->valid->get('q') });
};

1;

@@ views/base.tx
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<link rel="shortcut icon" href="<: $c.req.uri_for('/favicon.ico') :>" type="image/vnd.microsoft.icon" />
<link rel="stylesheet" href="<: $c.req.uri_for('/css/bootstrap.min.css') :>">
<title>[% module %]</title>
<style type='text/css'>
body {
  background-color: #fff;
  position: relative;
}
section {
  padding-top: 60px;
}
section > .row {
  margin-bottom: 10px;
}
.footer {
  background-color: #eee;
  min-width: 940px;
  padding: 30px 0;
  text-shadow: 0 1px 0 #fff;
  border-top: 1px solid #e5e5e5;
  -webkit-box-shadow: inset 0 5px 15px rgba(0,0,0,.025);
     -moz-box-shadow: inset 0 5px 15px rgba(0,0,0,.025);
/*          box-shadow: inset 0 5px 15px rgba(0,0,0,.025);
*/}
</style>
</head>
<body>

<div class="topbar">
<div class="topbar-inner">
<div class="container">
<a class="brand" href="<: $c.req.uri_for('/') :>">[% module %]</a>
<ul class="nav">
<li><a href="<: $c.req.uri_for('/') :>">Home</a></li>
</ul>
</div>
</div>
</div>

<div class="container">
<section>
<div class="page-header">
: block page_header -> { }
</div>
<div class="row">
<div class="span16">
: block content -> { }
</div>
</div>
</section>
</div>

<footer class="footer">
<div class="container">
<p class="pull-right"><a href="#">Back to top</a></p>
<p>Powered by Kossy</p>
</div>
</footer>

<script type="text/javascript" src="<: $c.req.uri_for('/js/jquery-1.7.1.min.js') :>"></script>
<script type="text/javascript" src="<: $c.req.uri_for('/js/bootstrap-modal.js') :>"></script>
<script type="text/javascript" src="<: $c.req.uri_for('/js/bootstrap-alerts.js') :>"></script>
</body>
</html>

@@ views/index.tx
: cascade base
: around page_header -> {
<h1><: $c.stash.site_name :></h1>
: }

: around content -> {
<h2><: $greeting :></h2>
: }


@@ app.psgi
use FindBin;
use lib "$FindBin::Bin/extlib/lib/perl5";
use lib "$FindBin::Bin/lib";
use File::Basename;
use Plack::Builder;
use [% module %]::Web;

my $root_dir = File::Basename::dirname(__FILE__);

my $app = [% module %]::Web->psgi($root_dir);
builder {
    enable 'ReverseProxy';
    enable 'Static',
        path => qr!^/(?:(?:css|js|images)/|favicon\.ico$)!,
        root => $root_dir . '/public';
    $app;
};

@@ Makefile.PL
use ExtUtils::MakeMaker;

WriteMakefile(
    NAME          => '[% module  %]',
    VERSION_FROM  => 'lib/[% module %].pm',
    PREREQ_PM     => {
        'Kossy' =>  '[% myver %]',
    },
    MIN_PERL_VERSION => '5.008001'
);

@@ t/00_compile.t
use strict;
use warnings;
use Test::More;

use_ok $_ for qw(
    [% module %]
    [% module %]::Web
);

done_testing;


