#!/usr/bin/perl

use strict;

use File::Find;
use Cwd;
use File::Path qw(make_path remove_tree);
use File::Spec;

my $project_root_dir  = getcwd();

$project_root_dir =  File::Spec->rel2abs($project_root_dir);

my %seen = ();

# reiniting spek app 
print "reiniting spek app ...\n";

open APP, ">", "$project_root_dir/speek.psgi" or die $!;

print APP <<HERE;

use parent 'Kelp';


HERE

if ( open INITFILE, "$project_root_dir/app.pm" ){

print "populate app.pm ...\n";

open APP, ">>", "$project_root_dir/speek.psgi" or die $!;

print APP "\n\n";

while (my $l =  <INITFILE>){
    print APP $l;
}

print APP "\n\n";

close APP;

close INITFILE;

}

finddepth(\&wanted, $project_root_dir );

my %routes;

sub wanted { 

    my $file = $_;

    if ($file =~ /^(get|post|update|delete)\.txt$/) {

        my $http_method = $1;

        return if $seen{$File::Find::name};

        my $resource_dir = $File::Find::dir;

        if ( open CODE, "$resource_dir/$http_method.pm" ){

            print "populate $http_method $resource_dir ...\n";

            my $r;

            s{^$project_root_dir}[] for $resource_dir;

            while (my $l =  <CODE>){
                chomp $l;
                push @{$routes{"$http_method $resource_dir"}}, $l ;
            }
            close CODE;
        }

        $seen{$File::Find::name} = 1;
   }

}


open APP, ">>", "$project_root_dir/speek.psgi" or die $!;


print APP <<'HERE' if keys %routes;

sub build {

    my $self = shift;
    my $r = $self->routes;

HERE


for my $k (keys %routes) {
    my ($m,$r) = split /\s+/, $k;
    $m = uc($m);

    s{/id}[/:id] for $r;
    s{/id/}[/:id/] for $r;

    my $code = join "\n\t", @{$routes{$k}};

    print APP <<HERE;
    \$r->add([ $m => '$r'  ] , sub {
        $code
    });

HERE


}

print APP "\n\n}\n\n" if keys %routes;

print APP <<'HERE';

my $app = __PACKAGE__->new;
$app->run;

HERE

close APP;


exec "plackup speek.psgi"

__END__

 $r->add( [ POST => '/postme' ], sub { 'i am post only!' }  );
