package Debian::PkgJs::Utils;

use strict;
use base 'Exporter';

our @EXPORT=qw(open_file main_package pjson component_list);

sub open_file {
    my $file = pop;
    die "Missing file arg" unless $file;
    my $f;
    open( $f, $file ) or die $!;
    my @lines = map {
        chomp;
        s/#.*$//;
        s/^\s*(.*?)\s*/$1/;
        $_ ? $_ : ();
    } <$f>;
    close $f;
    return @lines;
}

my ( %json, $main_p );

sub main_package {
    return ( $main_p ? $main_p : () ) if defined $main_p;
    return '.' unless -e 'debian/nodejs/main';
    my @lines = open_file('debian/nodejs/main');
    die 'Malformed debian/nodejs/main'       if @lines > 1;
    print STDERR "Missing main directory $lines[0]" if @lines and !-d $lines[0];
    $main_p = $lines[0] || '';
    return @lines;
}

# package.json cache
sub pjson {
    my $dir = pop;
    unless ( -e "$dir/package.json" ) {
        print STDERR "/!\\ $dir/package.json not found\n";
        return undef;
    }
    return $json{$dir} if $json{$dir};
    my $pkgjson;
    open $pkgjson, "$dir/package.json";
    my $content = join '', <$pkgjson>;
    close $pkgjson;
    $json{$dir} = JSON::from_json($content);
    if ( -e "debian/nodejs/$dir/name" ) {
        $json{$dir}->{name} =
          [ open_file("debian/nodejs/$dir/name") ]->[0];
    }
    return $json{$dir};
}

sub component_list {
    my ( @components, %packages );
    if ( -e 'debian/watch' ) {
        map { push @components, $1 if (/component=([\w\-\.]+)/) }
          open_file('debian/watch');
    }
    if ( -e 'debian/nodejs/additional_components' ) {
        print "Found debian/nodejs/additional_components\n";
        map {
            print 'Adding component(s): ' . join( ', ', glob($_) ) . "\n";
            push @components, glob($_)
        } open_file('debian/nodejs/additional_components');
    }
    foreach my $component (@components) {
        next if main_package() and $component eq main_package();
        if ( -d $component ) {
            my $package;
            eval { $package = pjson($component)->{name} };
            if ($@) {
                print STDERR "Unable to load $component: $@";
                next;
            }
            $packages{$component} = $package;
        }
        else {
            print STDERR "Can't find $component directory in " . `pwd`;
            next;
        }
    }
    return \%packages;
}
1;
