#!/mod/bin/jimsh

package require cgi
source /mod/webif/lib/setup
require epg.class spinner.class altrow settings.class

jqplugin highlight
header

require totop

set ct [cgi_get ct 0]
set crid [cgi_get crid ""]
set scrid [cgi_get scrid ""]

if {[cgi_exists term]} {
	set lterm [cgi_get term]

	if {[string match {CRID:*} $lterm]} {
		set crid [string range $lterm 5 end]
	} elseif {[string match {SCRID:*} $lterm]} {
		set scrid [string range $lterm 6 end]
	}
} elseif {$crid ne ""} {
	set _cgi(term) "CRID:$crid"
} elseif {$scrid ne ""} {
	set _cgi(term) "SCRID:$scrid"
}

require epg_search

[spinner new {
	text "Searching EPG..."
	size "1.2em"
	style "margin: 1em;"
	}] start

require epg_popup

set cmd "search"
if {$searchfull} { set cmd "searchall" }

set dedup 0
if {$ct > 0 } {
	set records [epg dbfetch dump -type $ct]
	if {[[settings] genrededup]} { set dedup 1 }
} elseif {$crid ne ""} {
	set records [epg dbfetch dump -crid $crid]
} elseif {$scrid ne ""} {
	set records [epg dbfetch dump -scrid $scrid]
} elseif {$searchterm ne ""} { 
	set records [epg dbfetch $cmd -term $searchterm]
} else {
	set records {}
}

set favlist [epg favlist]
set s [settings]
if {[$s service_style] eq "standard"} {
	set surl xservice
} else {
	set surl service
}

if {[llength $records] > 0} {
	puts {
	<table class=borders id=results style="clear: both;margin: 0.5em 0 0 0">
	<tr>
		<th>Date</th>
		<th colspan=3>Channel</th>
		<th>Programme</th>
		<th>Synopsis</th>
		<th></th>
	</tr>
	}
} else {
	puts "No results found."
}

proc rsort {v1 v2} {
	set v1s [$v1 get start]
	set v2s [$v2 get start]

	if {$v1s == $v2s} { return 0 }
	if {$v1s > $v2s } { return 1 }
	return -1
}

set seen {}
set i 0
foreach record [lsort -command rsort $records] {
	set ename [$record get name]
	if {$ename eq ""} continue

	if {$dedup} {
		if {$ename in $seen} continue
		lappend seen $ename
	}

	if {$favlist != "" && [$record get service_id] ni $favlist} {
		continue
	}
	altrow
	$record get_channel_info

	set ended [$record ended]

	if {$ended} {
		puts "<td nowrap class=blood>"
	} else {
		puts "<td nowrap>"
	}
	puts "
	    [clock format [$record get start] -format "%a %d %b %Y"]<br>
		[clock format [$record get start] -format "%H:%M %Z"]"
	puts "</td>"
	puts "<td>[$record get channel_num]</td>"
	puts "<td>[$record channel_icon 50]</td>"
	puts "<td nowrap>
	    <a href=/epg/$surl.jim?service=[$record get service_id]>
	    [$record get channel_name]
	    </a></td>"
	puts [$record cell]
	puts "<td>[$record get text]</td><td>[$record get warning]</td>"
	puts "</tr>"
}
puts "</table>"

if {$searchterm != ""} {
	puts "
		<script type=text/javascript>
		\$('#results').highlight('$searchterm');
		</script>
	"
}

epg cleanup
footer

