#!/usr/bin/perl

use strict;
use warnings;

###########################################################
#
# The script uploads flag 'is_selected' to table casp13.templates
# The data are retrieved from the file 
# /local/CASP13/RESULTS/TEMPLATES/templates.best1.
# The file should be prepared manually by organizers/assessors.
#
###########################################################

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

use ResultsTemplatesManager;

my $MANAGER = new ResultsTemplatesManager();
my $INFILE = "/local/CASP13/RESULTS/TEMPLATES/templates.best1";


&process();

#----------------------------
# SUBROUTINES
#----------------------------

# parse file and upload to the database
sub process{
    open F, "< $INFILE" || die "Failed to open file $INFILE\n";
    while(defined(my $l =<F>)){
	if ($l !~ m/^[TR]/){next;} # if line doesn't start with name of the target, skip it
	# "T0759-D1 1lm5B   99.30   14.71  100.00"
	my ($target, $templ) = split(/\s+/, $l);
	my $domain = 0;
	if ($target =~ m/^([TR][0-9]{4})-D([1-9]+)/){
		$target = $1;
		$domain = $2;
	}
	my %model = $MANAGER->get_new_model();
	$model{TARGET} = $target;
	$model{domain} = $domain;
	$model{name} = $templ;
	$model{is_selected} = 1;
	my $id = $MANAGER->exist_by_parameters(%model);
	if ($id > 0){
		$model{id} = $id;
		$MANAGER->update(%model);
	} else {
		next; # do nothing
	}
	printf ("%s -D%s %s %s\n", $model{TARGET}, $model{domain}, $model{name}, $model{id} );
#	last;
    }
    close F;
}



