#!/mod/bin/jimsh

package require cgi
source /mod/webif/lib/setup
require settings.class ts.class tvdb.class browse.class
jqplugin highlight tablesorter2

header

set file [cgi_get file -]
if {$file eq "-"} {
	footer
	exit
}
puts "
<script type=text/javascript>
var file = '$file';
var dir = '[file dirname $file]';
</script>
"
jscss episode.js

set search [cgi_get search ""]

if {[catch {set ts [ts fetch $file]}] || $ts eq "0"} {
	puts "Unable to load recording data."
	footer
	exit
}

# Causes other series information to be automatically populated
$ts clearepdata
set epname [$ts episode_name]
set series [$ts series_name]
set tvdb [$ts get tvdb_series]
set idata [$ts get tvdb_data]

browse breadcrumb [file dirname $file]
puts "
<fieldset>
<legend>Episode Search</legend>
	Search for:
	<input id=searchterm name=search value=\"$search\">
	<button id=tvdbepsearch>Search</button>
</fieldset>

<div>
<table class=keyval>
<tr>
	<th>Title</th>
	<td>[$ts get title]</td>
</tr><tr>
	<th>File</th>
	<td>[$ts get file]</td>
</tr><tr>
	<th>Detected&nbsp;Episode</th>
	<td>[$ts epstr] - $epname (<i>$series</i>)</td>
</tr><tr>
	<th>Found&nbsp;Using</th>
	<td>[$ts get tvdb_method]</td>
</tr><tr>
	<th>Synopsis</th>
	<td class=synopsis>[$ts get synopsis]</td>
</tr>
</table>
</div>
"

if {$search ne ""} {
	set matches [lmap i [$tvdb episodesearch $search] {
		lassign $i x id
		list $id 0
	}]
} else {
	set matches [$tvdb get _smatches]
}

if {![llength $matches]} {
	footer
	exit
}


puts "
<div>
<table class=\"results keyval borders\">
<thead>
<tr>
	<th data-sorter=false></th>
	<th>Score</th>
	<th>Ep.</th>
	<th>Name</th>
	<th data-sorter=false>Synopsis</th>
</tr>
</thead>
<tbody>
"

foreach match $matches {
	lassign $match episode_id score
	set ep [$tvdb episodebyid $episode_id]

	if {![llength $ep]} continue

	puts "<tr sid=$episode_id s=$ep(series) e=$ep(episode)><td>"

	if {[dict exists $ep thumb]} {
		puts "<img width=200 src=\"[tvdb bannerurl $ep(thumb)]\">"
	}
	puts "</td>
		<td>$score</td>
		<td>s$ep(series)e$ep(episode)</td>
		<td>	$ep(name)
			<br>
			<button class=select eid=$episode_id>Select</button>
		</td>
		<td>$ep(overview)</td>
	</tr>
	"
}

puts "
</tbody>
</table>
</div>
"

footer
