#!/bin/sh  
# \
exec oagwish "$0" "$@"

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]

APSStandardSetup

set CVSRevisionAuthor "\$Revision: 1.0 $ \$Author: SHANG $"

proc ReadData {args} {
    global dataDir
    set RFList {L1 L2 L3 L4 L5 L6} 
    eval global $RFList
    
    foreach RF $RFList {
        foreach name {VSWR1 VSWR2 VSWR3 ArcTrip} {
            set file $dataDir/${RF}$name.sdds
            if ![file exist $file] {
                set rows 0
                set ${RF}($name.rows) 0
            } else {
                set rows [exec sdds2stream -rows=bar $file]
                set ${RF}($name.rows) $rows
                set tripTimeList [exec sdds2stream -col=${name}TimeStamp $file]
                set commentList [exec sdds2stream -col=${name}Comment $file]
                for {set i 0} {$i<$rows} {incr i} {
                    set ${RF}($name.$i.time) [lindex $tripTimeList $i]
                    set ${RF}($name.$i.comment) [lindex $commentList $i]
                    set ${RF}($name.$i.newcomment) [lindex $commentList $i]
                    set ${RF}($name.$i.changed) 0
                }
            }
        }
    }
}

proc CreatFaultDisplayWidget {args} {
    set parent ""
    set RF ""
    APSParseArguments {parent RF}
    
    global dataDir $RF
    set nameList  {VSWR1 VSWR2 VSWR3 ArcTrip}
    set wList [APSTabFrame .tab -parent $parent -label "$RF RF Faults" \
                 -labelList $nameList \
                  -width 1350 -height 500]
    set index 0
    foreach name $nameList {
        set parent [lindex $wList $index]
        set ${RF}Scroll($name) [APSScroll .conscrol -parent $parent]
        
        set w $parent.conscrol.frame
        set rows [set ${RF}($name.rows)]
        for {set i 0} {$i<$rows} {incr i} {
            APSFrame .f$i -parent $w
            APSLabeledOutput .time -parent $w.f$i.frame -label "$RF/$name:" -textVariable ${RF}($name.$i.time) -width 25 \
              -packOption "-side left"
            APSLabeledEntry .comment -parent $w.f$i.frame -label "" -textVariable ${RF}($name.$i.newcomment) -width 125 \
              -packOption "-side left"
            bind $w.f$i.frame.comment.entry <Return> "UpdateComment -RF $RF -name $name -index $i"
        }
        incr index
    }
    
}

proc UpdateComment {args} {
    set RF ""
    set name ""
    set index ""
    APSParseArguments {RF name index}
    global $RF
    set oldComment [set ${RF}($name.$index.comment)]
    set newComment [set ${RF}($name.$index.newcomment)]
    
    if [string compare $oldComment $newComment]!=0 {
        set ${RF}($name.$index.comment) $newComment
        WriteCommentToFile -RF $RF -name $name -index $index
    }
}

proc WriteCommentToFile {args} {
    set RF ""
    set name ""
    set index ""
    APSParseArguments {RF name index}
    global dataDir $RF
    set file $dataDir/${RF}$name.sdds
    set tmpRoot /tmp/[APSTmpString]
    if {$name=="acrTrip"} {
        set col ArcTrip
    } else {
        set col $name
    }
    set comment [set ${RF}($name.$index.comment)]
    if [catch {exec sddsprocess $file -redefine=col,Index,i_row,type=long -pipe=out -nowarnings \
                 | sddsprocess -pipe=in $tmpRoot.1 -filter=col,Index,$index,$index -nowarnings  \
                 "-reprint=col,${col}Comment,[APSMakeSafeQualifierString $comment]" 
        exec sddsprocess $file -redefine=col,Index,i_row,type=long -pipe=out -nowarnings \
                 | sddsprocess -pipe=in $tmpRoot.2 "-filter=col,Index,$index,$index,!" -nowarnings 
        exec sddscombine $tmpRoot.1 $tmpRoot.2 -merge -pipe=out \
                 | sddssort -pipe=in -col=Index $file } result] {
        return -code error "Error updating $file: $result"
    }
    catch {exec rm ${file}~}
}

proc ReviewPrint {args} {
    set RF ""
    APSParseArguments {RF}
    global dataDir nameList RFList
    eval global $RFList
    
    set tmpRoot /tmp/[APSTmpString]
    set fileList ""
    foreach name {VSWR1 VSWR2 VSWR3 ArcTrip} {
        set file $dataDir/${RF}$name.sdds
        if [file exist $file] {
            if [catch {exec sddsprintout $dataDir/${RF}$name.sdds -col=*TimeStamp,format=%30s -col=*Comment \
                         "-title=\n\n$RF RF Faults -- $name Trip" $tmpRoot.$name } result] {
                return -code error "$result"
            }
            lappend fileList $tmpRoot.$name
        }
    }
    APSAddToTmpFileList -ID rffaults -fileList $fileList
    eval exec cat $fileList > $tmpRoot.print
    APSFileDisplayWindow .diff -fileName $tmpRoot.print -width 80 -height 30 -printCommand "enscript -r" \
      -deleteOnClose 1
    return
    set maxRows 0
    foreach name {VSWR1 VSWR2 VSWR3 ArcTrip} {
        set file $dataDir/${RF}$name.sdds
        if [file exist $file] {
            set ${name}Rows [exec sdds2stream -rows=bar $file]
            set ${name}TimeList [exec sdds2stream -col=${name}TimeStamp $file]
            set ${name}CommentList [exec sdds2stream -col=${name}Comment $file]
        } else {
            set ${name}Rows 0
        }
        if {[set ${name}Rows]>$maxRows} {
            set maxRows [set ${name}Rows]
        }
    }
    if !$maxRows {
        #now data for $RF
        return
    }
    APSWindow .review$RF -name "$RF RF Faults" -closeButton 1
    APSScrolledText .file -parent .review$RF.userFrame -width 165 -height 25  
    set text .review$RF.userFrame.file.text
   # APSDialogBoxAddButton .print -parent .review$RF -text Print \
    #  -command "APSPrint -cmd enscript -textWidget $text" \
    #  -contextHelp "Print contents of window using enscript command."
    #APSDialogBoxAddButton .printd -parent .review$RF -text Print... \
      #      -command "APSPrint -textWidget $text -cmd enscript"
    APSDialogBoxAddButton .printd -parent .review$RF -text Print... \
      -command "PrintFaults -RF $RF"
    
    $text insert end "           VSWR1                                 VSWR2                                  VSWR3                               ArcTrip                        \n"   
    
    set comLen 15
    set oneLen [expr 23 + 2 + $comLen]
    #time length is 19, 2 spaces, + comment len
    for {set i 0} {$i<$maxRows} {incr i} {
        set maxPrintRows 0
        foreach name {VSWR1 VSWR2 VSWR3 ArcTrip} {
            if {$i<[set ${name}Rows]} {
                set ${name}Time [lindex [set ${name}TimeList] $i]
                set ${name}Comment [lindex [set ${name}CommentList] $i]
                set len [string length [set ${name}Comment]]
                set ${name}PrintRows [expr int($len/$comLen)+1]
                if {$maxPrintRows < [set ${name}PrintRows]} {
                    set maxPrintRows [set ${name}PrintRows]
                }
            } else {
                set ${name}PrintRows 0
            }
        }
        
        for {set j 0} {$j<$maxPrintRows} {incr j} {
            foreach name {VSWR1 VSWR2 VSWR3 ArcTrip} {
                set printRows [set ${name}PrintRows]
                if {$j<$printRows} {
                    #insert time stamp 
                    set time [regsub -all {\"} [set ${name}Time] ""]
                    #regexp {([^.]*).}  $time b c
                    #set time $c
                    if {$j==0} {
                        $text insert end $time
                    } else {
                        for {set n 0} {$n<19} {incr n} {
                            $text insert end " "
                        }
                    }
                    #insert space
                    $text insert end "  "
                    #insert comment 
                    set start [expr $j * $comLen]
                    set end [expr ($j+1)*$comLen - 1]
                    set str [string range [set ${name}Comment] $start $end]
                    set len [string length $str]
                    $text insert end $str
                    set extraSpaces [expr $comLen - $len]
                   
                    if {$len<$comLen} {
                        for {set n 0} {$n<$extraSpaces} {incr n} {
                            $text insert end " "
                        }
                    }
                } else {
                    for {set n 0} {$n<$oneLen} {incr n} {
                        $text insert end " "
                    }
                }
                #insert more spaces between names
                $text insert end "    "
            }
            $text insert end "\n"
        }
    
    }
    
}

proc PrintFaults {args} {
    set RF ""
    APSParseArguments {RF}

    global dataDir nameList
    set tmpRoot /tmp/[APSTmpString]
    foreach name $nameList {
        if [file exist $dataDir/${RF}$name.sdds] {
            if [catch {exec sddsprintout -col=${name}TimeStamp -col=${name}Comment $dataDir/${RF}$name.sdds $tmpRoot.$name \
                         "-title=$RF RF $name faults" } result] {
                return -code error "Error printing $RF $name: $result"
            }
            exec lpr $tmpRoot.$name
            APSAddToTmpFileList -ID rffault -fileList $tmpRoot.$name
        }
    }
}

set nameList {VSWR1 VSWR2 VSWR3 ArcTrip}
set dataDir /home/helios/oagData/linac/Linac_RF_Faults/data

APSApplication . -name LinacRFFaultReview -version $CVSRevisionAuthor \
  -overview {Linac RF faults logger reviewer.}

ReadData

set RFList {L1 L2 L3 L4 L5 L6}
set tabList [APSTabFrame .review -parent .userFrame -label "" \
    -labelList $RFList \
    -width 1350 -height 600]

foreach RF $RFList widget $tabList {
    
    CreatFaultDisplayWidget -parent $widget -RF $RF
    
    APSButton .review1 -parent $widget -text "Review/Print" -command "ReviewPrint -RF $RF"

}

