# Conflict resolution between two networked TiVos using using a modified version of
# Christopher R. Wingert's manrec.itcl on the other TiVo
# Version 0.1
# Chris Gunn, 2004
# Adapted from Stuart Anderton's confres.itcl
# Big chunks 'repurposed' from various TiVoWeb modules
#
# 27/04/2006 - v0.2 [Patch] - Remembers the last remote tivo
#                             Displays correctly under Firefox
#
# Starting procedure, gets address of remote TiVo
proc action_confresManual {chan path env} {
   global source_dir
   set todotypelabels "Conflicts {Adjacent Different Channels}"
   set todotypevals   "History Active"  
   set todotype "History"
   set remote_tivo "tivo1"
   # Load any settings found in the configuration file
   if {[file exists $source_dir/modules/confresManual.cfg]} {
      catch {source $source_dir/modules/confresManual.cfg}
   }
   puts $chan [html_start "Conflict Resolver"]
   puts $chan "Attempt to schedule conflicts on a second TiVo"
   puts $chan [html_form_start "GET" "/findconfsManual"]
   puts $chan [html_table_start "" "" ""]
   puts $chan [tr "" [td "Remote TiVo to find recording space on: "] [td [html_form_text 1 35 "tivoname" "$remote_tivo"]]]
   puts $chan [tr "" [td "Number of days ahead to look: "] [td [html_form_text 1 35 "daysahead" "7"]]]
   puts $chan [tr "" [td "ToDo type to schedule"] [td [html_form_select "todotype" $todotypevals $todotypelabels $todotype]]]
   puts $chan [tr "" [td "Show resolved conflicts"] [td [html_form_checkbox "showresolved" ""]]]
   puts $chan [tr "" [td ""] [td [html_form_input "submit" "Save" "Next"]]]
   puts $chan [html_table_end]
   puts $chan [html_form_end]	
   puts $chan [html_end]
}
# Find unresolved conflicts and pass them to other TiVo
proc action_findconfsManual {chan path env} {
   global db
   global tzoffset
   global remote_tivo
   global source_dir
   eval $env
   set conflicts {}
   
   set othertivourl "http://$tivoname/manrec"
   puts $chan [html_start "Conflict Resolver Manual Recording"]
   # nothing is sent when checkboxes aren't checked
   if {[catch {if {$showresolved == "on"} {}}] == 1} {
      set showresolved "off"
   }
   
   if {$todotype == "Active"} {
      puts $chan "Found the following shows in adjacent time slots on different channels:"
   } else {
      puts $chan "Found the following unresolved conficts:"
   }
   puts $chan [html_table_start "" "" ""]
   puts $chan [tr "" [td "Title"] [td "Channel"] [td "Date"] [td "Quality     Force if conflict"] [td ""]]
   
   set recqual 75
   set mr_qualvals "0 40 75 100"
   set mr_quallabs "Basic Medium High Best"
   set yesnolabels "Yes No"
   set yesnovals   "1 0"  
   set forcerecord 0
   set remote_tivo "tivo1"
   # Load any settings found in the configuration file
   if {[file exists $source_dir/modules/confresManual.cfg]} {
      catch {source $source_dir/modules/confresManual.cfg}
   }
   if {$remote_tivo != $tivoname} {
      set    fd [open "$source_dir/modules/confresManual.cfg" w]
      puts  $fd {#}
      puts  $fd {# The name or IP address of the remote TiVo}
      puts  $fd {#}
      puts  $fd "set remote_tivo \"$tivoname\""
      puts  $fd {#}
      puts  $fd {# The default recording quality (must be 0, 40, 75 or 100)}
      puts  $fd {#}
      puts  $fd "set recqual \"$recqual\""
      close $fd
   }
   
   set prevendtime 0
   set prevcallsign 0
   set prevrow ""
   ForeachMfsFile fsid name type "/Recording/$todotype" "" {
      set recdate [split $name ":"]
      if {$todotype == "Active"} {
	 set datepos 2
	 set timepos 1
      } else {
	 set datepos 1
	 set timepos 0
      }
      regsub {^(-?)0+([1-9])} [lindex $recdate $datepos] {\1\2} thetime
      set rectime [expr [lindex $recdate $timepos] * 86400 + $thetime ]
      if {$rectime > [expr [clock seconds] + $daysahead * 86400]} {
	 break
      }
      
      if {$rectime > [clock seconds]} {
	 
	 RetryTransaction {
	    set rec [db $db openid $fsid ]
	    set creason [dbobj $rec get CancelReason]
	    set errorstring [dbobj $rec get ErrorString]
	    set showing [dbobj $rec get Showing]
	    set duration [dbobj $showing get Duration]
	    set station [dbobj $showing get Station]
	    set callsign [dbobj $station get CallSign]
	    set program [dbobj $showing get Program]
	    set title [dbobj $program get Title]
	    set title [string trim $title "{}"]
	    set id [dbobj $program get TmsId]
	    set id2 [dbobj $program fsid]
	    set description [dbobj $program get Description]
	    set description [string trim $description "{}"]
	    set episodetitle [dbobj $program get EpisodeTitle]
	    set episodetitle [string trim $episodetitle "{}"]
	    set rating 0
	    # rating is messing up display when there is no rating table on other TiVo
	    # uncomment if you want ratings and it works on your TiVo
	    # set rating [dbobj $showing get TvRating]
	 }
	 set resolvederror "{Transfered to another TiVo original time was $rectime duration was $duration}"
	 if {$errorstring != $resolvederror || $showresolved == "on"} {
	    
	    if {$errorstring != $resolvederror 
		&& [string first "Transfered to another TiVo original time was" $errorstring] > -1 } {
	       set schedulechanged "
(Schedule has changed)"
	    } else {
	       set schedulechanged ""
	    }
	    if {$errorstring == $resolvederror && $showresolved == "on"} {
	       set schedulechanged "
(Resolved)"
	    }
	    
	    if {$prevcallsign == 0} {
	       set prevcallsign callsign
	    }
	    if {$todotype == "Active" || $creason == 20 || $schedulechanged != ""} {
	       set alt [alt_showing $id $id2]
	       if {$todotype == "Active" || $alt == "" || $schedulechanged != ""} {
		  set showbutton 0
		  if {($todotype == "Active" && $rectime == $prevendtime
		       && $callsign != $prevcallsign) || $creason == 20 
		      || $schedulechanged != ""} {
		     set showbutton 1
		  }
		  #adjust for timezone
		  set starttime [expr $rectime + $tzoffset]
		  set endtime [expr $starttime + $duration]
		  
		  set strdelbutton [td "[html_form_start "GET" "/delresolvedconf"]
				   [html_form_hidden "conflict" $fsid]
				   [html_form_hidden "rectime" $rectime]
				   [html_form_hidden "duration" $duration]
				   [html_form_hidden "tivoname" $tivoname]
				   [html_form_hidden "daysahead" $daysahead]
				   [html_form_hidden "todotype" $todotype]
				   [html_form_hidden "showresolved" $showresolved]
				   [html_form_input "submit" "submit" "Delete"]
				   [html_form_end]"]
		  
		  set wodatetz [expr $starttime / 86400]
		  set wodatetz [expr $wodatetz * 86400]
		  set wotimetz [expr ($starttime - $wodatetz) / 3600 ]
		  set womin [expr ($starttime - $wodatetz - ($wotimetz * 3600)) / 60 ]
		  set woduration [expr $duration / 60]
		  
		  set strrecbutton [td "[html_form_start "GET" $othertivourl]
				   [html_form_hidden "titlestr" $title]
				   [html_form_hidden "episodetitlestr" $episodetitle]
				   [html_form_hidden "descriptionstr" $description]
				   [html_form_hidden "chnsel" ""]
				   [html_form_hidden "callsign" $callsign]
				   [html_form_hidden "wodatetz" $wodatetz]
				   [html_form_hidden "wotimetz" $wotimetz]
				   [html_form_hidden "womin" $womin]
				   [html_form_hidden "durationstr" $woduration]
				   [html_form_hidden "ratingstr" $rating]
				   [html_form_hidden "repeat" "once"]
				   [html_form_select "recqual\" style=\"width:11ex" $mr_qualvals $mr_quallabs $recqual]
				   [html_form_select "forcerecord\" style=\"width:8ex" $yesnovals $yesnolabels $forcerecord]
				   [html_form_input "submit" "submit" "Record"]
				   [html_form_end]"]
		  
		  set strrow [tr "" "[td "$title $schedulechanged"]
			     [td $callsign]
			     [td "[clock format $starttime -format {%a %1d %1b %H:%M}] - [clock format $endtime -format %H:%M]"]
			     $strrecbutton $strdelbutton" ]
      unset strrecbutton strdelbutton
		  if {$showbutton == 1 || $schedulechanged != ""} {
		     if {$prevrow != ""} {
			puts $chan $prevrow
		     }
		     puts $chan $strrow
		     set prevrow ""
		  } else {
		     if {$prevrow == ""} {
			puts $chan [tr "" [td " "] [td " "] [td " "] [td " "] [td " "]]
			puts $chan [tr "" [td " "] [td " "] [td " "] [td " "] [td " "]]
		     }
		     set prevrow $strrow
		  }
		  set prevendtime [expr $rectime + $duration]
		  set prevcallsign $callsign
	       }
	    }
	 }
      }
   }
   
   puts $chan [html_table_end]
   puts $chan [html_end]
}
proc action_delresolvedconf {chan path env} {
   eval $env
   puts $chan [html_start "Delete Resolved Conflict"]
   puts $chan "Deleting conflict..."
   set success [DeleteCanceledTodoRec $conflict 20 "Transfered to another TiVo original time was $rectime duration was $duration"]
   if {$success == 1 } {
      puts $chan "Done"
   } else {
      puts $chan "There was a problem deleting the conflict."
   }
   puts $chan [html_form_start "GET" "/findconfsManual"]
   puts $chan [html_form_hidden "tivoname" $tivoname]
   puts $chan [html_form_hidden "daysahead" $daysahead]
   puts $chan [html_form_hidden "todotype" $todotype]
   puts $chan [html_form_hidden "showresolved" $showresolved]
   puts $chan [html_form_input "submit" "Save" "Back to unresolved conficts"]
   puts $chan [html_form_end]	
   
   puts $chan [html_end]
}
proc DeleteCanceledTodoRec { recfsid cancelreason errorstring } {
   global db
   
   set canceldate [expr [clock seconds] / 86400]
   set canceltime [expr [clock seconds] % 86400]
   
   RetryTransaction {
      set rec [db $db openid $recfsid]
      set state [dbobj $rec get State]
      dbobj $rec set CancelReason $cancelreason
      dbobj $rec set CancelDate $canceldate
      dbobj $rec set CancelTime $canceltime
      dbobj $rec set ErrorString $errorstring
      dbobj $rec set State 2
   }
   return 1
}
register_module "confresManual" "Conflict Resolve" "Schedule conflicts on another TiVo using Manual Recording"