#!/usr/bin/perl -w

use strict;
use warnings;

use SReview::Talk;
use SReview::Config::Common;
use SReview::Files::Factory;
use DBI;
use File::Basename;

my $talkid = shift;
my $config = SReview::Config::Common::setup();
my $talk = SReview::Talk->new(talkid => $talkid);
my $collname = $config->get("inject_collection");
my $input;
if($collname eq "input") {
	$input = SReview::Files::Factory->create("input", $config->get("inputglob"), $config);
} elsif($collname eq "pub") {
	$input = SReview::Files::Factory->create("intermediate", $config->get("pubdir"), $config);
} else {
	$input = SReview::Files::Factory->create($collname, $config->get("extra_collections")->{$collname}, $config);
}
die "talk not in correct stream" unless $talk->active_stream eq 'injected';
my $db = DBI->connect($config->get("dbistring"), '', '') or die "Cannot connect to database!";
my $st = $db->prepare("SELECT filename FROM raw_files WHERE room = ? AND stream = ? AND filename LIKE ?");
$st->execute($talk->roomid, $talk->active_stream, '%' . dirname($talk->relative_name) . '%');
my $row = $st->fetchrow_arrayref;
my $inputfile = $input->get_file(relname => $row->[0]);
my @command = ("sreview-inject", "-t", $talkid, "-i", $inputfile->filename);
if(!$talk->get_flag("keep_audio")) {
	push @command, "-a";
}
system(@command);
