#!/usr/bin/perl

use strict;
use warnings;
$| = 1;

use Proc::Daemon;
use File::Basename;

use lib qw(./libs);

our $Config;
BEGIN {
	use API::Config;
	$Config = $API::Config::Config;
}
use lib ($Config->{'Website_libs'});

use ECS::Config;
use ECS::SQL;

use ECS::Product::PricingImport;
use ECS::Product::PricingImport::Parse;
use ECS::Product::PricingImport::Init;
use ECS::Product::PricingImport::Commit;
use ECS::Product::PricingImport::PreProcess;
use ECS::Product::PricingImport::PreProcessor;

my $website_config = \%ECS::Config::c;
my $pricing_file_dir = $website_config->{'pricing_import'}->{'file_dir'};

print "Started ".fileparse(__FILE__)." \n";

while (1) {
	
	# Process Commits first priority
	my $commit_files = processDir({
		'dir' => 'commit', 
		'errorDir' => 'error',
		'processor' => \&ECS::Product::PricingImport::Commit::start
	});
	
	# Process Inits second priority
	my $init_files = processDir({
		'dir' => 'init',
		'errorDir' => 'error',
		'processor' => \&ECS::Product::PricingImport::Init::start
	});
	
	my $preprocess_files = processDir({
		'dir' => 'preprocess/init',
		'errorDir' => 'preprocess/error',
		'processor' => \&ECS::Product::PricingImport::PreProcessor::start
	});
	
	# If nothing was done, sleep for 10s, then check for work
	if (
		not $commit_files
		and not $init_files
		and not $preprocess_files
	) {
		sleep(10);
	} else {
		Time::HiRes::usleep(10);
	}
	
	# Otherwise, check for more work immediately
}

sub processDir {
	my $p = shift;
	
	my $dir = $pricing_file_dir.'/'.$p->{'dir'};
	my @files = <$dir/*>;
	
	if (!@files) {
		# Nothing to do this time
		return 0;
	}
	
	foreach my $path (@files) {
		next unless -f $path;
		my $filename = fileparse($path);
		my $itemID = $filename;
		$itemID =~ s/\D//g;
	
		print 'Processing '.$p->{'dir'}.' on '.$filename."\n";
		
		my ($success, $error) = $p->{'processor'}($itemID);
		
		if ($success) {
			print "Success\n";
		} else {
			print 'Failed ('.$error.")\n";
		}
		
		# If the file did not move (status did not change)
		if (-e $path) {
			# move it to the error dir
			rename(
				$path,
				$pricing_file_dir.'/'.$p->{'errorDir'}.'/'.fileparse($path)
			);
		}
		return @files;
	}
	
}
