#!/usr/bin/env perl
use LWP::Simple;
use JSON;
use utf8;
use warnings;
use constant debug => $ENV{DEBUG};
use App::gh;
use App::gh::Utils;
use App::gh::Command;

$|++;
binmode STDOUT, ':utf8';

my $screen_width = 92;


sub print_list {
    my @lines = @_;

    my $column_w = 0;

    map { 
        $column_w = length($_->[0]) if length($_->[0]) > $column_w ; 
    } @lines;

    for my $arg ( @lines ) {
        my $title = shift @$arg;

        my $padding = int($column_w) - length( $title );

        if ( $ENV{WRAP} && ( $column_w + 3 + length( join " ",@$arg) ) > $screen_width ) {
            # wrap description
            my $string = $title . " " x $padding . " - " . join(" ",@$arg) . "\n";
            $string =~ s/\n//g;

            my $cnt = 0;
            my $firstline = 1;
            my $tab = 4;
            my $wrapped = 0;
            while( $string =~ /(.)/g ) {
                $cnt++;

                my $c = $1;
                print $c;

                if( $c =~ /[ \,]/ && $firstline && $cnt > $screen_width ) {
                    print "\n" . " " x ($column_w + 3 + $tab );
                    $firstline = 0;
                    $cnt = 0;
                    $wrapped = 1;
                }
                elsif( $c =~ /[ \,]/ && ! $firstline && $cnt > ($screen_width - $column_w) ) {
                    print "\n" . " " x ($column_w + 3 + $tab );
                    $cnt = 0;
                    $wrapped = 1;
                }
            }
            print "\n";
            print "\n" if $wrapped;
        }
        else { print $title;
            print " " x $padding;
            print " - ";
            print join " " , @$arg;
            print "\n";
        }

    }
}



# my $config = parse_config $ENV{HOME} . "/.gitconfig";
# use Data::Dumper; warn Dumper( $config );

my $act = shift;
$SIG{INT} = sub {
    exit;
};

if( ! $act || $act eq 'help' ) 
{
    App::gh::Command->dispatch( 'help' , @ARGV );
    exit;
}
elsif( $act eq 'search' || $act eq 's' ) {
    my $keyword = shift;
    my $json = get 'http://github.com/api/v2/json/repos/search/' . $keyword;

    my $result = decode_json( $json );

    my @ary = ();
    for my $repo ( @{ $result->{repositories} } ) {
        my $name = sprintf "%s/%s", $repo->{username} , $repo->{name};
        my $desc = $repo->{description};
        push @ary, [ $name , $desc ];
    }

    print_list @ary;
}
elsif( $act eq 'clone' || $act eq 'c' ) {
    my $user;
    my $repo;

    $user = shift;
    if( $user =~ /\// ) {
        ($user,$repo) = split /\//,$user;
    }
    else {
        $repo = shift;
    }

    my $attr = shift || 'ro';
    my $uri;
    if( $attr eq 'ro' ) {
        $uri = sprintf "git://github.com/%s/%s.git" , $user , $repo;
    }
    elsif( $attr eq 'ssh' ) {
        $uri = sprintf "git\@github.com:%s/%s.git" , $user , $repo;
    }
    print $uri . "\n";
    system( qq{git clone $uri} );
}



elsif( $act eq 'pullfork' || $act eq 'pull' || $act eq 'pf' ) 
{
    App::gh::Command->dispatch('pull', @_ );
}
elsif( $act eq 'list' ) 
{
    my $acc = shift;
    my $json = get 'http://github.com/api/v2/json/repos/show/' . $acc;
    my $data = decode_json( $json );
    my @lines = ();
    for my $repo ( @{ $data->{repositories} } ) {
        my $repo_name = $repo->{name};
        push @lines , [  
            $acc . "/" . $repo->{name} ,
            ($repo->{description}||"")
        ];
    }
    print_list @lines;
}
elsif( $act eq 'cloneall' || $act eq 'ca' ) {
    my $acc = shift;
    my $attr = shift || 'ro';

    _info "Getting repository list from github: $acc";
    my $json = get 'http://github.com/api/v2/json/repos/show/' . $acc;
    my $data = decode_json( $json );

    _info "Will clone repositories below:";
    for my $repo ( @{ $data->{repositories} } ) {
        print "  " . $repo->{name} . "\n";
    }


    for my $repo ( @{ $data->{repositories} } ) {
        my $repo_name = $repo->{name};
        my $local_repo_name = $repo_name;
        $local_repo_name =~ s/\.git$//;

        my $uri;
        if( $attr eq 'ro' ) {
            $uri = sprintf "git://github.com/%s/%s.git" , $acc , $repo_name;
        }
        elsif( $attr eq 'ssh' ) {
            $uri = sprintf "git\@github.com:%s/%s.git" , $acc , $repo_name;
        }
        print $uri . "\n";

        if( -e $local_repo_name ) {
            print "Updating " . $local_repo_name . " ...\n";
            qx{ cd $local_repo_name ; git pull origin master };
        }
        else {
            print "Cloning " . $repo->{name} . " ...\n";
            qx{ git clone -q $uri };
        }
    }
}
elsif( $act eq 'network' ) {
    die "Git config not found." if ( ! -e ".git/config" );
    App::gh::Command->dispatch('network', @_ );
}
elsif( $act eq 'fork' ) {
    App::gh::Command->dispatch('fork', @_ );
}
