#!/mod/bin/jimsh

source /mod/webif/lib/setup
require queue.class json settings.class system.class

httpheader "application/json"

set s [settings]
set autolast [$s autolast]
set autofreq [$s autofreq]
set qrunning $([string length [queue pids]] ? 1 : 0)
if {$autofreq == 0} { set autofreq 10 }
puts "{"
puts "  \"autofreq\": \"$autofreq\","
puts "  \"autolast\": \"[clock format $autolast] ([clock format \
    $([clock seconds] - $autolast) -format %T] ago)\","
puts "  \"qrunning\": \"$qrunning\","

puts "  \"data\": \["
set flag 0
foreach q [queue all] {
	set name [string map {
			"/mnt/hd2/My Video/" ""
			"/media/drive1/Video/" ""
			"/media/" ""
			".ts" ""
		} [$q get file]]
	set submitted [clock format [$q get submitted] \
	    -format {%d/%m/%Y %H:%M:%S}]
	set last [$q get last]
	if {$last ne "" && $last ne "0"} {
		set last [clock format $last -format {%d/%m/%Y %H:%M:%S}]
	} else {
		set last ""
	}

	set start [$q get start]
	if {$start ne "0"} { set start $([clock seconds] - $start) }

	if {$flag} { puts "," } else { incr flag }
	puts "{"
	puts "  \"qid\": [$q get id],"
	puts "  \"submitted\": \"$submitted\","
	puts "  \"last\": \"$last\","
	puts "  \"file\": \"[::json::escape $name]\","
	puts "  \"action\": \"[::json::escape [$q get action]]\","
	puts "  \"args\": \"[::json::escape [$q get args]]\","
	puts "  \"status\": \"[$q get status]\","
	puts "  \"start\": \"$start\","
	puts "  \"log\": \"[::json::escape [$q get log]]\","
	if {[$q get runtime] > 0} {
		set time [clock format [lindex [split [$q get runtime] .] 0] \
		    -format "%T"]
		puts "  \"runtime\": \"$time\","
	} else {
		puts "  \"runtime\": \"0\","
	}
	puts "  \"retries\": \"[$q get retries]\""
	puts -nonewline "}"
}
puts "\n]"
puts "}"

