package SVN::Hooks::TagBugzilla;

use strict;
use warnings;
use SVN::Hooks;

use Exporter qw/import/;
my $HOOK = 'TAG_BUGZILLA';
our @EXPORT = qw/TAG_BUGZILLA/;

our $VERSION = $SVN::Hooks::VERSION;

sub TAG_BUGZILLA {
    my $conf = $SVN::Hooks::Confs->{$HOOK};
    die "Invalid: odd number of arguments" if @_ % 2;
    while (my ($path_regexp, $config) = splice(@_,0,2) ) {
      push @{$conf->{options}}, { regexp => $path_regexp,
				  %$config };
    }

    $conf->{'post-commit'} = \&post_commit;
    $conf->{'pre-commit'} = \&pre_commit;
    return 1;
};

$SVN::Hooks::Inits{$HOOK} = sub {
    return { options => [] };
};

sub pre_commit {
  my ($self, $svnlook) = @_;
  my @dir_changed = $svnlook->dirs_changed;
  for my $conf (@{$self->{options}}) {
    if (grep $_ =~ $conf->{regexp}, @dir_changed) {
      warn "Log message missing Valid bugzilla bug #" unless $svnlook->log_msg =~ m/BZ#(\d+)/;
    }
  }
}

sub post_commit {
  my ($self, $svnlook) = @_;
  return unless (my (@bug) = $svnlook->log_msg =~ m/BZ#(\d+)/);
  require BZ::Client;
  require BZ::Client::Bugzilla;
  require BZ::Client::Product;
  require BZ::Client::Bug;
  die "Not our BZ::Client" unless $BZ::Client::VERSION =~ m/barkani/;

  my @dir_changed = $svnlook->dirs_changed;
  for my $conf (@{$self->{options}}) {
    if (grep $_ =~ $conf->{regexp}, @dir_changed) {

      my $bz;
      eval {
	$bz = BZ::Client->new(
			      url => $conf->{bugzilla_url},
			      user => $conf->{bugzilla_user},
			      password => $conf->{bugzilla_password},
			     );

	my $message;
	{
	  local $\="\n";
	  open my $fh, '>', \$message;

	  $fh->print( "SVN Revision: " , $svnlook->rev);
	  $fh->print( "Author: ", $svnlook->author, "\n");
	  $fh->print( $svnlook->log_msg );

	  my @added = $svnlook->added();
	  if (@added) {
	    print $fh "Added: $_" for @added;
	  }

	  my @changed = $svnlook->changed();
	  if (@changed) {
	    print $fh "Changed: $_" for @changed;
	  }

	  my @deleted = $svnlook->deleted();
	  if (@deleted) {
	    print $fh "Deleted: $_" for @deleted;
	  }

	  my @updated = $svnlook->updated();
	  if (@updated) {
	    print $fh "Updated: $_" for @updated;
	  }

	  $fh->close();
	}

	my ($bug) = $bz->get_bugs(\@bug);
	my $confirm = $bug->add_comment($bz, {comment => $message });

      };
      die "$@" if $@;
    }
  }
  return;
}

1;


