#!/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.1 $ \$Author: borland $"

set dataDir /home/helios/oagData/monitoring/shutters
cd $dataDir

APSApplication . -name AbsorberWaterReview -version $CVSRevisionAuthor 
set statusText "Ready."
APSScrolledStatus .status -parent .userFrame -textVariable statusText -width 60 \
    -height 3

proc SetStatusText {text} {
    global statusText 
    set statusText  "$text"
    update
}

proc MakeDateTimeFrame {widget args} {
    set parent .
    set rootname ""
    APSStrictParseArguments {parent rootname glitchMode}
    set label "Date/Time Range of Interest"

    APSFrame $widget -parent $parent -label $label
    set w $parent$widget.frame

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

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

proc SetDateTimeToToday {args} {
    set rootname ""
    set hour 0
    ResetDataFileList
    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
}

set dataFileList ""
set dataFileListIsOld 1
proc ResetDataFileList {} {
    global dataFileList  dataFileListIsOld
    set dataFileList ""
    set dataFileListIsOld 1
}


set existingDataFile ""
set lastFileList ""
set fileListUpdateTime 0
proc FindFiles {} {
    global StartMonth StartYear StartDay StartHour
    global EndMonth EndYear EndDay EndHour existingDataFile lastFileList fileListUpdateTime dataDir
    global dataFileListIsOld StartTime EndTime
    set Rootname shutters

    foreach item $lastFileList {
        set mtime [file mtime $item]
        if {$mtime>$fileListUpdateTime} {
            set dataFileListIsOld 1
            break
        }
    }

    if !$dataFileListIsOld {
        return $existingDataFile
    }

    set dataFileList  \
      [APSFindFilesBetweenDates -tailsOnly 1 \
         -rootname ${Rootname}- \
         -directory $dataDir \
         -startDateList [APSFormatDate -year $StartYear -month $StartMonth \
                           -day $StartDay -dateFormat list] \
         -endDateList [APSFormatDate -year $EndYear -month $EndMonth \
                         -day $EndDay -dateFormat list] ]
    SetStatusText "[llength $dataFileList] files found."
    set lastFileList $dataFileList
    set fileListUpdateTime [exec timeconvert -now | token -last]
    set tmpFile /tmp/[APSTmpString]
    set existingDataFile $tmpFile
    switch [llength $dataFileList] {
        0 {
            return ""
        }
        1 {
            if [string compare [file extension $dataFileList] .gz]==0 {
                set tmpFile $tmpFile.gz
                set existingDataFile $tmpFile
            }
            APSAddToTempFileList $tmpFile
            if [catch {exec cp $dataFileList $tmpFile} result] {
                SetStatusText "copy problem: $result"
                return ""
            }
        }
        default {
            APSAddToTempFileList $tmpFile
            SetStatusText "Merging..."
            if [catch {eval exec sddscombine -merge $dataFileList -overwrite $tmpFile} result] {
                SetStatusText "Processing problem: $result"
                return ""
            }
        }
    }

    set dataFileListIsOld 0
    return $tmpFile
}

proc ListOpenShutters {} {
    global dataFileList
    global StartMonth StartYear StartDay StartHour
    global EndMonth EndYear EndDay EndHour existingDataFile lastFileList fileListUpdateTime dataDir
    global dataFileListIsOld StartTime EndTime

    SetStatusText "Working..."
    set file [FindFiles]
    if ![string length $file] {
        SetStatusText "No data found."
        return
    }

    if [catch {APSConvertTimeToHours $StartHour} hour] {
        SetStatusText "Invalid starting hour: $StartHour"
        return
    }
    set StartTime \
      [exec timeconvert \
         -breakDown=year=$StartYear,day=$StartDay,month=$StartMonth,hour=$hour]
    if [catch {APSConvertTimeToHours $EndHour} hour] {
        SetStatusText "Invalid ending hour: $EndHour"
        return
    }
    set EndTime \
      [exec timeconvert \
         -breakDown=year=$EndYear,day=$EndDay,month=$EndMonth,hour=$hour]

    if [catch {exec sddscombine -merge $file -pipe=out \
                 | sddsprocess -pipe -nowarning -filter=column,Time,$StartTime,$EndTime \
                 -process=*Closed,min,%sMin \
                 | sddscollapse -pipe \
                 | sddscollect -pipe -collect=suffix=ClosedMin \
                 | sddsprocess -pipe -filter=column,ClosedMin,-0.1,0.1 -nowarning \
                 -reedit=column,Rootname,%/Shutter// \
                 | sddsprintout -pipe=in $file.print \
                 -column=Rootname,label=Beamline \
                 "-title=Shutters that were open between $StartYear/$StartMonth/$StartDay@$StartHour and $EndYear/$EndMonth/$EndDay@$EndHour"} result] {
        SetStatusText $result
        return
    }
    APSFileDisplayWindow [APSUniqueName .] -fileName $file.print
}


MakeDateTimeFrame .date -parent .userFrame
APSButton .listopen -parent .userFrame \
  -text "List Open Shutters" -command ListOpenShutters -contextHelp \
  "Lists all shutters that were open at any time during the period indicated."

