#!/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)]
APSDebugPath

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

APSApplication . -name LinacRFRecoveryActivityReview -version $CVSRevisionAuthor \
  -overview "Displays activity data for the linac RF recovery activity, showing the plot for each chosen area."

set dataDir /home/helios/oagData/logDaemonData/linacRFRecovery
set resDataDir /home/helios/oagData/logDaemonData

set statusText "Ready..."
APSScrolledStatus .status -parent .userFrame -textVariable statusText -width 60 \
  -contextHelp "Displays number of launched plots." 
update

set logsList [glob -nocomplain ${dataDir}/steeringAudit.log.*]
lappend logsList [glob -nocomplain $resDataDir/linacRFRecovery.log]
set ordLogsList [lsort $logsList]
set refFile /home/helios/oagData/logDaemonData/publicFiles/SteeringAudit.ref

proc InitViewTime {} {
    global statusText Start Finish typeList columnList L1 L2 L3 L4 L5 L6
    global ordLogsList printoutString
    global StartYear StartMonth StartDay StartHour dataDir
    global EndYear EndMonth EndDay EndHour instanceList

    set intervalString "$StartMonth/$StartDay/$StartYear $StartHour and $EndMonth/$EndDay/$EndYear $EndHour"

    set fileList ""
    set instanceList ""
    setOpenCloseViewBut 0
    set statusText "Working..."
    update
    set tempFile /tmp/[APSTmpString]

    #This is in the case of hour selection in format 0:00:00
    set sHour [APSConvertTimeToHours ${StartHour}] 
    set eHour [APSConvertTimeToHours ${EndHour}]
    set lowLimit [exec timeconvert -breakDown=year=${StartYear},month=${StartMonth},day=${StartDay},hour=$sHour]
    set highLimit [exec timeconvert -breakDown=year=${EndYear},month=${EndMonth},day=${EndDay},hour=$eHour]
    
    if {$lowLimit >= $highLimit} {
        set statusText "Wrong time frame selection!"
         setOpenCloseViewBut 1
        return
    }

    set processFileList \
      [APSFindFilesBetweenDates -tailsOnly 0 -extensionList {"*"}\
         -directory $dataDir \
         -startDateList [APSFormatDate -year $StartYear -month $StartMonth \
                           -day $StartDay -dateFormat list] \
         -endDateList [APSFormatDate -year $EndYear -month $EndMonth \
                         -day $EndDay -dateFormat list] ]
    if [llength $processFileList] {
        if [catch {eval exec sddscombine $processFileList -pipe=out -merge \
                     | sddsprocess -pipe -noWarnings \
                     -filter=column,Time,$lowLimit,$highLimit \
                     | sddssort -pipe -col=Time \
                     | sddstimeconvert -pipe  \
                     -breakdown=col,Time,year=Year,month=Month,day=Day,hour=Hour,text=TimeStamp \
                     | sddsprocess -pipe=in $tempFile \
                     -reedit=col,Host,S/./D20/ -nowarnings \
                     -reedit=col,TimeStamp,S/./D20 \
                 } result] {
            setOpenCloseViewBut 1
            set statusText $result
            return
        }
    } else {
        set statusText "No log data found."
        return 
    }
    set rows [exec sdds2stream -rows=bar $tempFile]
    if !$rows {
        setOpenCloseViewBut 1
        set statusText "NO log data found."
        return
    }
    set cols 0
    set colList ""
    set tempRoot /tmp/[APSTmpString]
    
    foreach type $typeList column $columnList {
        # beamline type: ID BM AM
        global $type
        if [set $type] {
            lappend colList $column
            incr cols
        }
    }
    set intervalString "$StartMonth/$StartDay/$StartYear $StartHour and $EndMonth/$EndDay/$EndYear $EndHour"
    
    set printcol "-col=TimeStamp,format=%25s -col=Action,format=%8s"
    foreach col $colList {
        if {[regexp "PFN" $col] || [regexp "Atten" $col]} {
            if {$col=="PFNFinalValue"} {
                append printcol " -col=$col,format=%13s,label=PFNSCRValue"
            } else {
                append printcol " -col=$col,format=%13s"
            }
        } elseif [regexp "Power" $col] {
            if {$col=="KlystronForwardPower"} {
                append printcol " -col=$col,format=%13s,label=KlyForPower"
            } else {
                append printcol " -col=$col,format=%13s,label=SledForPower"
            }
        } elseif {$col=="SCRFile"} {
            append printcol " -col=$col,format=%28s"
        } else {
            append printcol " -col=$col,format=%10s"
        }
    }
    foreach RF {L1 L2 L3 L4 L5 L6} {
        if [set $RF] {
            APSAddToTmpFileList -ID results -fileList $tempFile.$RF
            if [catch {exec sddsprocess $tempFile -match=col,RF=$RF  -nowarnings $tempFile.$RF } result] {
                set statusText "Error processing $RF : $result"
                setOpenCloseViewBut 1
                return
            }
            set rows [exec sdds2stream -rows=bar $tempFile.$RF]
            if !$rows {
                set statusText "No data found for $RF"
                continue
            }
            APSAddToTmpFileList -ID results -fileList $tempFile.$RF.print
            if [catch {eval exec sddsprintout -width=200 $tempFile.$RF $tempFile.$RF.print $printcol \
                         \"-title=$RF recovery status between dates $intervalString\" } result] {
                set statusText "Error printing $RF : $result"
                continue
            }
            APSFileDisplayWindow .review$RF -packOption "-side bottom" -width 200 \
              -fileName $tempFile.$RF.print  -contextHelp \
              "Displays the recovery state of $RF at chosen time range."
        }
    }
    
    setOpenCloseViewBut 1
    set statusText "Done."
    update
    
}

# makes frame for date/time selection widgets (for range
# of dates to process)

proc MakeDateTimeFrame {widget args} {
    set parent .

    APSStrictParseArguments {parent}

    set label "Date/Time Range of Interest"

    APSFrame $widget -parent $parent -label $label

    set w $parent$widget.frame

    APSDateTimeAdjEntry .startDate -parent $w \
      -yearVariable StartYear \
      -monthVariable StartMonth \
      -dayVariable StartDay \
      -hourVariable StartHour \
      -label "Starting date/time (year, month, day, hour): " \
      -defaultHour 0 \
      -command ResetMonDataFileList
    APSDateTimeAdjEntry .endDate -parent $w \
      -yearVariable EndYear \
      -monthVariable EndMonth \
      -dayVariable EndDay \
      -hourVariable EndHour \
      -label "Ending date/time (year, month, day, hour):   " \
      -defaultHour 24 \
      -command ResetMonDataFileList

    SetDateTimeToToday -rootname Start -hour 0
    SetDateTimeToToday -rootname End  -hour 24
}

proc SetDateTimeToToday {args} {
    set rootname ""
    set hour 0

    ResetMonDataFileList
    APSStrictParseArguments {rootname hour}

    global ${rootname}Month ${rootname}Year ${rootname}Day ${rootname}Hour
    
    APSDateBreakDown -dayVariable ${rootname}Day -yearVariable ${rootname}Year \
      -monthVariable ${rootname}Month -twoDigitYear 0 -leadingZeros 0
    set ${rootname}Hour $hour
}

proc ResetMonDataFileList {} {
    global DataFileList 

    set DataFileList " "
    update
}

proc setOpenCloseViewBut {state} {
    global f
    if $state {
        APSEnableButton $f.butt.button
    } else {
        APSDisableButton $f.butt.button
    } 
}

proc cleanUpFiles {} {
    APSDeleteTempFiles -ID plot
    APSDeleteTempFiles -ID results
    APSDeleteTempFiles -ID timeInfo
}

MakeDateTimeFrame .timeFrame -parent .userFrame  

APSFrame .chckbut -parent .userFrame -width 80 -packOption "-side top" \
  -label "view type:"
set w .userFrame.chckbut.frame


set RFList {L1 L2 L3 L4 L5 L6}
foreach RF $RFList {
    set $RF 0
}
set L1 1

APSCheckButtonFrame .type -parent $w -label "RF:" -allNone 1 \
    -orientation horizontal -buttonList $RFList  \
    -variableList $RFList \
    -packOption "-side top" -contextHelp \
    "Selection of a type of a beam line from the Storage Ring." 

set typeList {User Host SCRFile PFNSCRValue PFNsetpoint PFNValue Attenuator KlystronForwardPower SledForwardPower}
set columnList {User Host SCRFile PFNFinalValue PFNsetpoint PFNReadback Attenuator KlystronForwardPower SledForwardPower}
foreach var $typeList {
    set $var 1
}

APSCheckButtonFrame .bframe -parent $w -label "Review type" \
  -buttonList $typeList -allNone 1 \
  -variableList $typeList  \
  -orientation horizontal -limitPerRow 5 \
  -contextHelp "Selection a type to view the value." 

APSFrame .butframe -parent .userFrame -packOption "-side top"

set f .userFrame.butframe.frame



APSButton .butt -parent $f -text "View" \
  -packOption "-side left" \
  -command InitViewTime -contextHelp \
  "Invokes data analysis from steeringAudit log files for the chosen beam lines in the selected time frame." 

#APSButton .plot -parent $f -text "Plot" -packOption "-side left" \
#  -command {MakePlot -file $steeringActivity} -contextHelp \
 # "Makes a plot from the existing data for each chosen beam line separately."

dp_atexit append cleanUpFiles

