# Batch EXecutor 2.0 -- Jobs
# (c) 2011 Martin Mares <mj@ucw.cz>

use strict;
use warnings;

package BEX::Job;

use POSIX ();

our $job_cnt = 0;

sub new($;$) {
	my ($class, $id) = @_;
	my $job = { };
	bless $job;
	if (defined $id) {
		$job->{'ID'} = $id;
	} else {
		$job_cnt++;
		$job->{'ID'} = POSIX::strftime("%Y%m%d-%H%M%S-$$-$job_cnt", localtime);
	}
	$job->{'Subject'} = '(no subject)';
	return $job;
}

sub new_from_file($$;$) {
	my ($class, $file, $header_only) = @_;
	my $job = { };
	open T, '<', $file or die "Cannot open $file: $!";
	while (<T>) {
		chomp;
		/^$/ and last;
		/^([A-Z][A-Za-z0-9-]*):\s*(.*)/ or die "Cannot load $file: Header syntax error";
		!defined $job->{$1} or die "Cannot load $file: Header $1 re-defined";
		$job->{$1} = $2;
	}
	if (!$header_only) {
		my @cmds = <T>;
		$job->{'body'} = join("", @cmds);
	}
	close T;
	$job->{'Subject'} //= '?';
	$job->{'ID'} or die "Cannot load $file: Missing ID";
	$job->{'ID'} !~ /\.[a-z]+$/ or die "Cannot load $file: Invalid ID syntax";
	return bless $job;
}

sub id($) {
	return $_->{'ID'};
}

sub attr($$;$) {
	my ($job, $attr, $val) = @_;
	$job->{$attr} = $val if defined $val;
	return $job->{$attr};
}

sub dump($) {
	my ($job) = @_;
	for my $k (sort keys %$job) {
		print "$k: ", $job->{$k}, "\n";
	}
}

sub save($;$) {
	my ($job, $fn) = @_;
	-d "tmp" or mkdir "tmp" or die "Cannot create directory tmp: $!";
	$fn //= 'tmp/' . $job->id;
	open T, '>', $fn or die "Cannot create $fn: $!";
	for my $k (sort grep { /^[A-Z]/ } keys %$job) {
		print T "$k: ", $job->{$k}, "\n";
	}
	print T "\n";
	print T $job->{'body'} if defined $job->{'body'};
	close T;
	return $fn;
}

42;
