#!/usr/bin/perl
use strict;
use warnings;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use MIME::Parser;
use MIME::Entity;
use MIME::Body;
use Getopt::Long;

use lib qw(Core);
use lib qw(Classes);

use Configuration;
use LocalConfiguration;

use Submission;
use Logger;

my $SCRIPTNAME = 'parce_PDB_annotator.pl';

my $logger = new Logger();

my $input_file = '';
my $skip = '';

my $isparams = GetOptions(
	"file|f=s"         => \$input_file,
	"skip|skiped=s" => \$skip
);

my $EMAIL;
my $INPUT;
if($input_file ne '') {
    open($INPUT, $input_file);
    $EMAIL = $INPUT;
} else {
    $EMAIL = \*STDIN;
}

# generate unique id for predictionfile


my $prediction_filename = '';
my $prediction_file = '';
my $message_filename = '';
my $message_file = '';
my $uid = 0;
do {
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);        
    my $date = sprintf("%s_%s_%s-%s-%s",($mon+1), $mday, $hour, $min, $sec);
    $uid = md5_hex(sprintf("casp%s%s%s%s%s", $mday, $hour, $min, $sec, rand(9999)));
    $prediction_filename = sprintf("%s.prediction", $uid);


######### AK: 04/29/10 - Change dirs here

    $prediction_file = sprintf("%s/%s", $LOCAL_CONFIG->{SUBMITED_PREDICTIONS_DIR}, $prediction_filename);
    $message_filename = sprintf("%s.message", $uid);
    $message_file = sprintf("%s/%s", $LOCAL_CONFIG->{MESSAGES_PREDICTIONS_DIR}, $message_filename);
} while((-e $prediction_file) || (-e $message_file));


# save original email message to file

if(open(MESSAGE, sprintf("> %s", $message_file))) {
	while(<$EMAIL>) {
	    print(MESSAGE $_);
	}
	close(MESSAGE);
	system(sprintf("chmod a+r %s", $message_file));
} else {
	$logger->error($SCRIPTNAME, sprintf("Email message wasn't saved! File: %s", $message_file));
	exit;
}

open(my $SAVED_MESSAGE, $message_file);

# process email
my $parser = new MIME::Parser();
$parser->ignore_errors(1);
$parser->output_to_core(1);

my $entity = $parser->parse($SAVED_MESSAGE);
my $error = ($@ || $parser->last_error);

my $header = $entity->head;

my $sender_email = $header->get('From');
my $body = join('',  @{$entity->body});

# remove trailing whitespace from body
$body =~ s/\s*\n+$//s;

my $EMAIL_REGEXP = '[\w\-\.\_]+@[\w\-\.\_]+';
if($sender_email =~ /\s*($EMAIL_REGEXP)\s*/) {
	$sender_email = $1;
}

chomp($sender_email);
chomp($body);


#TODO READ attachment or add this part in to Submition.pm class 


# save prediction to file
if(open(PREDICTION, sprintf("> %s", $prediction_file))) {
	print(PREDICTION $body);
	close(PREDICTION);
	system(sprintf("chmod a+r %s", $prediction_file));
} else {
	$logger->error($SCRIPTNAME, sprintf("Annotation wasn't saved to file! File: %s", $prediction_file));
	exit;
}



#my $submission = new Submission($sender_email, $prediction_filename, 'email', 0, $uid, $skip);
#my $result = $submission->process();
#
#if($result) {
#	$logger->info($SCRIPTNAME, sprintf("Prediction was submitted successfully! Email: %s, File: %s", $sender_email, $prediction_filename));
#	#$submission->notification_success("Submission ACCEPTED");
#} else {
#	$logger->warning($SCRIPTNAME, sprintf("Prediction submittion failed! Email: %s, File: %s", $sender_email, $prediction_filename));
#}

close($SAVED_MESSAGE);
