# LJ's Utilities module.
#
# Based very heavily on other parts of TiVoWeb!
#
# LJ @ http://www.tivocommunity.com/
#
# 29Dec02 11:48  v1.0  Slotfree module.
# 30Dec02 17:30  v2.0  New search code; return icon with conflict details.
# 30Dec02 22:38  v2.1  Show conflict.png instead of broken link for conflicts.
# 30Dec02 23:20  v2.2  Shorter tooltips!
# 31Dec02 13:26  v2.3  Show four different icons for conflicts.
# 01Jan03 17:24  v2.4  Different icon for a free slot; ignore suggestions when deciding if a slot is free; remove alt text.
# 25Jan03 16:50  v3.0  Add thumbs modification module.
# 16Feb03 15:38  v3.1  Add get_thumbimagelj - standard proc, but also returns confidence value.
# 23Feb03 10:50  v3.2  Scan for existing PrefsElement before creating a new one.
# 18May03 15:34  v3.3  Add logic for Type 16 thumbs data.
# 16Aug03 19:43  v3.4  Include currently recording programme (if any) in slotfree calculation.
# 31Jan04 10:04  v3.5  Fixes a bug in the thumbs module when reseting thumbs.  Thanks Adlopa!
# **** REMOVE /n FROM TOOLTIP !!! ****
proc slotfree {seconds duration chan} {
  global db
  global images
  set slotstartdate [expr $seconds / 86400]
  set slotstarttime [expr $seconds - ($slotstartdate * 86400)]
  set slotenddate [expr ($seconds + $duration) / 86400]
  set slotendtime [expr ($seconds + $duration) - ($slotenddate * 86400)]
  set foundearlierrec 0
  set foundlaterrec 0
  set slotfull 0
  set reason ""
  set recs [mfs scan "/Recording/Active" -start "3:[expr $slotstartdate - 1]:" -count 2]
  scan [lindex [lindex $recs 0] 1] "%d:%d:%d:%d" rectype recstartdate recstarttime recfsid
  scan [lindex [lindex $recs 1] 1] "%d:%d:%d:%d" dummy recstartdate recstarttime recfsid
  set lasttest [lindex [lindex $recs 0] 1]
  if {[info exists recstartdate] == 0} {
    return "[img "title=\"Slot may be free; could not find any records.\"" "slotfree.png"]"
  }
  while { [expr ($recstartdate * 86400) + $recstarttime] < $seconds } {
    set recs [mfs scan "/Recording/Active" -start "[lindex [lindex $recs 1] 1]" -count 2]
    if { [llength $recs] < 2 } {
      break
    }
    scan [lindex [lindex $recs 1] 1] "%d:%d:%d:%d" dummy recstartdate recstarttime recfsid
    set lasttest [lindex [lindex $recs 0] 1]
    set foundearlierrec 1
  }
  while { $lasttest != "" } {
    set recs [mfs scan "/Recording/Active" -start $lasttest -count 2]
    set lasttest [lindex [lindex $recs 1] 1]
    scan [lindex [lindex $recs 0] 1] "%d:%d:%d:%d" dummy recstartdate recstarttime recfsid
    if { $recstartdate > $slotenddate } {
      set foundlaterrec 1
      break
    }
    if { ($recstartdate == $slotenddate) && ($recstarttime >= $slotendtime) } {
      set foundlaterrec 1
      break
    }
         set rec [db $db openid $recfsid]
    set rectype [dbobj $rec get SelectionType]
    if { $rectype == 6 } {
      continue
    }
    set startpad [dbobj $rec get StartPadding]
    set endpad [dbobj $rec get EndPadding]
    set showing [dbobj $rec get Showing]
    set recdur [dbobj $showing get Duration]
    set recend [expr ($recstartdate * 86400) + $recstarttime + $startpad + $endpad + $recdur]
    set recenddate [expr $recend / 86400]
    set recendtime [expr $recend - ($recenddate * 86400)]
    if { $recenddate < $slotstartdate } {
      set foundearlierrec 1
      continue
    }
    if { ($recenddate == $slotstartdate) && ($recendtime <= $slotstarttime) } {
      set foundearlierrec 1
      continue
    }
    incr slotfull 1
    set recstartsecs [expr ($recstartdate * 86400) + $recstarttime]
    if {$::lang == "en"} {
      set starttimestr [ftime $recstartsecs "%H:%M"]
    } else {
      set starttimestr [ftime $recstartsecs "%l:%M %P"]
    }
    set recendsecs [expr $recend]
    if {$::lang == "en"} {
      set endtimestr [ftime $recendsecs "%H:%M"]
    } else {
      set endtimestr [ftime $recendsecs "%l:%M %P"]
    }
    set station [dbobj $showing get Station]
    set recchannel [dbobj $station get CallSign]
    set program [dbobj $showing get Program]
    set recseries [dbobj $program get Title]
# \n or " " here:
    set reason "$reason$starttimestr-$endtimestr $recchannel: $recseries.\n"
  }
  set reason [string trimright $reason]
  regsub -all {\{} $reason "" reason
  regsub -all {\}} $reason "" reason
  if { $slotfull > 0 } {
# \n or " " here:
    return "[img "title=\"$slotfull scheduled:\n$reason\"" "conflict[expr {$slotfull > 4 ? "4" : "$slotfull"}].png"]"
  } else {
    if { ($foundlaterrec == 1) || ([llength $recs] != 2) } {
      return "[img "title=\"No recordings currently scheduled in this slot.\"" "slotfree.png"]"
    } else {
      return "[img "title=\"Slot may be free ;) Send LJ this error message: E$foundearlierrec$foundlaterrec:$recstartdate:$recstarttime:$slotenddate:$slotendtime\"" "slotfree.png"]"
    }
  }
}
proc action_thumbs { chan objectid env } {
  global db
  set fsid ""
  eval $env
  puts $chan [html_start "Modify Thumbs"]
  if { $fsid == "" } {
    set ethmblabels "3 2 1 0 -1 -2 -3 Unset"
    set ethmbvals   "3 2 1 0 -1 -2 -3 -999"
    set thmblabels "3 2 1 0 -1 -2 -3"
    set thmbvals   "3 2 1 0 -1 -2 -3"
    if {[string index $objectid 0] == "/"} {
      set objectid [string range $objectid 1 end]
    }
    RetryTransaction {
      set series [db $db openid $objectid]
      set title [strim [dbobj $series get Title]]
      set score [dbobj $series get ThumbData]
    }
    puts $chan [h2 $title]
    if { $score == "" } {
      puts $chan "No Thumb Rating Currently Set"
      set numthumbs 1
      set thumbtype "Not"
    } else {
      set thumbdata [ReadableThumbs $score]
      scan $thumbdata "%s %d %d" thumbtype numthumbs thumbconf
      puts $chan [html_table_start "" "" ""]
      puts $chan [tr "ALIGN=CENTER" [th "COLSPAN=3" "Current Setting"]]
      puts $chan [tr "ALIGN=CENTER" [th "Thumbs"] [th "Type"] [th "Confidence"]]
      puts $chan [tr "ALIGN=CENTER" [td $numthumbs] [td $thumbtype] [td $thumbconf]]
      puts $chan [html_table_end]
    }
    puts $chan [html_form_start "POST" "/thumbs" "name=\"setthumbs\""]
    puts $chan [html_table_start "" "" ""]
    if { $thumbtype == "Explicit" || $thumbtype == "Implied" } {
      puts $chan [tr "" [td "Set Explicit Thumb Rating: "] [td "width=30%" [html_form_select "newthmb" $ethmbvals $ethmblabels $numthumbs]]]
    } else {
      puts $chan [tr "" [td "Set Explicit Thumb Rating: "] [td "width=30%" [html_form_select "newthmb" $thmbvals $thmblabels $numthumbs]]]
    }
    puts $chan [html_table_end]
    puts $chan [html_form_input "hidden" "fsid" $objectid]
    puts $chan [html_form_input "hidden" "orgthmb" $numthumbs]
    puts $chan [html_form_input "hidden" "title" $title]
    puts $chan [html_form_input "hidden" "thumbtype" $thumbtype]
    puts $chan [html_form_input "submit" "submit" "Set"]
    puts $chan [html_form_end]
  } else {
    set thumbsdir15 "/Preference/a/15"
    set thumbsdir16 "/Preference/a/16"
    puts $chan [h2 $title]
    if { $thumbtype == "Explicit" && $orgthmb == $newthmb } {
      puts $chan "Thumbs Already Explicitly Set To $newthmb ;)"
    } else {
      if { $newthmb == -999 } {
        RetryTransaction {
          set series [db $db openid $fsid]
          set serverid [dbobj $series get ServerId]
          dbobj $series set ThumbData "0x10000000"
          set thmbrec [db $db open "$thumbsdir15/$serverid"]
          dbobj $thmbrec markasrubbish
          regsub -all {[^a-zA-Z0-9]} $title "" titlesearch
          set thm16rec [lindex [get_fsidbyprefix "$thumbsdir16" "$titlesearch"] 0]
          if { $thm16rec != "" } {
            set thmbrec [db $db openid $thm16rec]
            puts $chan "
(You have previously recorded this series)
"
            dbobj $thmbrec markasrubbish
          }
        }
        # Supress events for versions >=6 -- rbautch
        if {$::version < 6} {
        	event send $TmkEvent::EVT_DATA_CHANGED $TmkDataChanged::VIEWER_PREFERENCES $serverid
        }
        puts $chan "
Thumbs Now Unset"
      } else {
        switch -- $newthmb {
          3 {set xthmbval "0x100303ff"}
          2 {set xthmbval "0x100302ff"}
          1 {set xthmbval "0x100301ff"}
          0 {set xthmbval "0x100300ff"}
          -1 {set xthmbval "0x1003ffff"}
          -2 {set xthmbval "0x1003feff"}
          -3 {set xthmbval "0x1003fdff"}
        }
        scan $xthmbval %x thmbval
        RetryTransaction {
          set series [db $db openid $fsid]
          set serverid [dbobj $series get ServerId]
          dbobj $series set ThumbData $thmbval
          if { [catch {set thmbrec [db $db open "$thumbsdir15/$serverid"]}] != 1 } {
            set Version [dbobj $thmbrec get Version]
            dbobj $thmbrec set Version [expr $Version + 1]
            dbobj $thmbrec set Thumbsness $thmbval
            regsub -all {[^a-zA-Z0-9]} $title "" titlesearch
            set thm16rec [lindex [get_fsidbyprefix "$thumbsdir16" "$titlesearch"] 0]
            if { $thm16rec != "" } {
              set thmbrec [db $db openid $thm16rec]
              puts $chan "
(You have previously recorded this series)
"
              set Version [dbobj $thmbrec get Version]
              dbobj $thmbrec set Version [expr $Version + 1]
              dbobj $thmbrec set Thumbsness $thmbval
            }
          } else {
            set thmbrec [db $db create PrefsElement]
            dbobj $thmbrec set Type 15
            dbobj $thmbrec set IntKeyValue 1
            dbobj $thmbrec set Viewer a
            dbobj $thmbrec set Vector 0
            dbobj $thmbrec add Vector 0
            dbobj $thmbrec add Vector 0
            dbobj $thmbrec add Vector 0
            dbobj $thmbrec add Vector 0
            dbobj $thmbrec add Vector 0
            dbobj $thmbrec add Vector 0
            dbobj $thmbrec set StringKeyValue $serverid
            dbobj $thmbrec set Item $series
            dbobj $thmbrec set Thumbsness $thmbval
            if { $::version >= 3 } {
              regsub -all {[^a-zA-Z0-9]} $title "" titlesearch
              set thm16rec [lindex [get_fsidbyprefix "$thumbsdir16" "$titlesearch"] 0]
              if { $thm16rec != "" } {
                set thmbrec [db $db openid $thm16rec]
                puts $chan "
(You have previously recorded this series)
"
                set Version [dbobj $thmbrec get Version]
                dbobj $thmbrec set Version [expr $Version + 1]
                dbobj $thmbrec set Thumbsness $thmbval
              }
            } else {
              set norerec [lindex [get_fsidbyprefix "/Recording/NoReRecord" "[expr $serverid + 1]:"] 0]
              if { $norerec != "" } {
                set norerec [db $db openid $norerec]
                puts $chan "
(You have previously recorded this series)
"
                set noshow [dbobj $norerec get Showing]
                set progid [dbobj $noshow gettarget Program]
                set progiddb [dbobj $noshow get Program]
                set progid [string range $progid 0 [expr [string first "/" $progid] - 1]]
                set thmbrec [db $db create PrefsElement]
                dbobj $thmbrec set Version 1
                dbobj $thmbrec set Type 16
                dbobj $thmbrec set IntKeyValue $progid
                dbobj $thmbrec set Viewer a
                dbobj $thmbrec set Thumbsness $thmbval
                dbobj $thmbrec set Vector 0
                dbobj $thmbrec add Vector 0
                dbobj $thmbrec add Vector 0
                dbobj $thmbrec add Vector 0
                dbobj $thmbrec add Vector 0
                dbobj $thmbrec add Vector 0
                dbobj $thmbrec add Vector 0
                dbobj $thmbrec set StringKeyValue $title
                dbobj $thmbrec set Item $progiddb
              }
            }
          }
        }
        # Supress events for versions >=6 -- rbautch
        if {$::version < 6} {
        	event send $TmkEvent::EVT_DATA_CHANGED $TmkDataChanged::VIEWER_PREFERENCES $serverid
        }
        puts $chan "
Thumbs Value Set To $newthmb"
      }
    }
  }
}
proc get_thumbimagelj {score} {
  set thumbdata [ReadableThumbs $score]
  scan $thumbdata "%s %d %d" thumbtype numthumbs thumbconf
  if {$thumbtype == "Predicted"} {
    switch -- $numthumbs {
      -3 {set imagenum 14}
      -2 {set imagenum 15}
      -1 {set imagenum 16}
      1 {set imagenum 17}
      2 {set imagenum 18}
      3 {set imagenum 19}
      default {set imagenum -1}
    }
  } else {
    switch -- $numthumbs {
      -3 {set imagenum 9}
      -2 {set imagenum 6}
      -1 {set imagenum 4}
      1 {set imagenum 12}
      2 {set imagenum 2}
      3 {set imagenum 7}
      default {set imagenum -1}
    }
  }
  return "$imagenum $thumbconf"
}