package Orchard::Accounting::JIRA;

use strict;
use warnings;

use base 'Class::Accessor';

use Git;
use FileHandle;

use lib '/var/app/orchard/collab/jgetter/perllib';
use Orchard::Session;

__PACKAGE__->mk_accessors(qw/branch outdir repo ticket version/);

sub new {
    my $class = shift;
    my $jira  = shift;
    my $vers  = shift;
    my $odir  = shift || 'art_relations';
    my $self  = {};
    bless $self, $class;
    $self->_init( $jira, $vers, $odir );
    $self;
}

sub _init {
    my $self = shift;
    my $jira = 'ACC-' . shift;
    my $vers = shift;
    my $odir = shift;
    $odir = "/Users/denk002/projects/database/${odir}/build/changelog/dml";

    my $branch = $jira . '-' . $vers;

    my $repo = Git->repository($odir);

    my $currentBranch = $repo->command( 'rev-parse', '--abbrev-ref', 'HEAD' );
    chomp($currentBranch);

    if ( $currentBranch ne $branch ) {
        logMessage( 'fatal', "Need to create $odir branch [$branch] - current branch is $currentBranch" );
        exit;
    }

    $self->branch($branch);
    $self->outdir($odir);
    $self->repo($repo);
    $self->ticket($jira);
    $self->version($vers);

}

sub finish {
    my $self = shift;
    my $file = shift;
	my $body = shift;
	$self->printfile($file,$body);
	$self->showfile($file);
	$self->printstatus();
}

sub getfilepath {
    my $self = shift;
    my $name = shift;
    my $ext  = shift || 'sql';
    my $ver  = $self->version;
	my $tic  = $self->ticket;
    $self->outdir . "/${tic}-${ver}_${name}.${ext}";
}

sub printstatus {
	my $self = shift;
	map { logMessage('info', "$_") } $self->repo->command('status');
}

sub printfile {
    my $self = shift;
    my $file = shift;
    my $body = shift;
    logMessage( 'info', "Printing $file" );
    my $outfile = FileHandle->new( $file, 'w' );
    $outfile->print($body);
    $outfile->close;
}

sub showfile {
    my $self = shift;
    my $file = shift;
    logMessage( 'info', "cat $file" );
    system("cat $file");
}


1;
