#!/usr/bin/env perl

# PODNAME: get_pauseid_distributions

use strict;
use warnings FATAL => 'all';
use feature 'say';
use utf8;
use open qw(:std :utf8);

use Data::Printer;
use ElasticSearch;
use LWP::Simple;
use JSON;

sub get_es {
    my $es = ElasticSearch->new(
        no_refresh  => 1,
        servers     => 'api.metacpan.org',
    );

    return $es;
}

sub get_distributions_user {
    my ($pause_id) = @_;

    my $data = get_es()->search(
        index  => 'v0',
        type   => 'release',
        fields => [qw(
            name
            author
            distribution
            status
        )],
        query  => {
            filtered => {
                query  => { match_all => {} },
                "filter" => {
                    "and" => [
                        {
                            "term" => {
                                author => $pause_id,
                            }
                        },
                        {
                            "term" => {
                                "status" => "latest"
                            }
                        }
                    ]
                },
            },
        },
        size => 100,
    );

    my @d;

    foreach my $el (@{$data->{hits}->{hits}}) {
        push @d, $el->{fields}->{distribution};
    }

    return @d;
}

sub get_distribution_repository {
    my ($d) = @_;

    my $json = get("http://api.metacpan.org/v0/release/$d");
    my $data = from_json($json);

    my $repository_url = $data->{resources}->{repository}->{url};

    return $repository_url;
}

sub main {

    my $pause_id = $ARGV[0];

    if (not defined $pause_id) {
        say "You should run it as `$0 PAUSEID`";
        exit 1;
    }

    my @distributions = get_distributions_user($pause_id);

    say 'namespace,name,source';

    foreach my $d (@distributions) {
        my $url = get_distribution_repository($d);

        my $module = $d;
        $module =~ s/-/::/g;

        if (defined $url) {
            say 'perl,'
                . $module . ','
                . $url
                ;
        } else {
            warn "WARNING: no info about repostitory url for $d\n";
        }
    }

}
main();

__END__

=pod

=encoding UTF-8

=head1 NAME

get_pauseid_distributions

=head1 VERSION

version 1.0.0

=head1 AUTHOR

Ivan Bessarabov <ivan@bessarabov.ru>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Ivan Bessarabov.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut