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

APSApplication . -name ComputeBeamlineDownTime -version $CVSRevisionAuthor \
      -overview {This application computes the downtime during any time peroid (after 10/19/2004, when the SR desired and actual modes are added to logonchange). For the case earlier than 10/19/2004, use BeamlineDownTimeCalculator.}

proc SetStatus {text args} {
    global status
    set status "[clock format [clock seconds] -format %H:%M:%S] $text"
    update      
}

proc GetBeamlineList {args} {
    global sectorList missingList logDirectory ControlNameIndex
    
    set names [exec sdds2stream $logDirectory/EPS.loc -col=ControlName]
    for {set i 0} {$i<[llength $names]} {incr i} {
        set ControlNameIndex([lindex $names $i]) $i
    }
    if [catch {exec sddsprocess $logDirectory/EPS.loc -pipe=out \
                 -match=col,ControlName=*:ID:BLEPS:SPER \
                 -scan=col,Beamline,ControlName,EPS:%ld,type=long \
                 | sddssort -pipe -col=Beamline \
                 | sdds2stream -pipe -col=Beamline } IDBeamlineList] {
        return -code error $IDBeamlineList
    }
    if [catch {exec sddsprocess $logDirectory/EPS.loc -pipe=out \
                 -match=col,ControlName=*:BM:BLEPS:SPER \
                 -scan=col,Beamline,ControlName,EPS:%ld,type=long \
                 | sddssort -pipe -col=Beamline \
                 | sdds2stream -pipe -col=Beamline } BMBeamlineList] {
        return -code error "$BMBeamlineList"
    }
    set sectorList [lsort -unique -integer [concat $IDBeamlineList $BMBeamlineList]]
    set IDMissingList ""
    set BMMissingList ""
    set index 1
    foreach sector $sectorList {
        if {[lsearch -exact $IDBeamlineList $sector]<0} {
            lappend IDMissingList S${index}ID
        }
        if {[lsearch -exact $BMBeamlineList $sector]<0} {
            lappend BMMissingList S${index}BM
        }
        incr index
    }
    set missingList [concat $IDMissingList $BMMissingList]
}

proc SetDateTimeToToday {args} {
    set hour 0
    set rootname ""
    APSStrictParseArguments {hour rootname}
    global todayMonth todayYear todayDay 
    global ${rootname}Month ${rootname}Year ${rootname}Day ${rootname}Hour
    
    APSDateBreakDown -dayVariable todayDay -yearVariable todayYear \
      -monthVariable todayMonth -twoDigitYear 0 -leadingZeros 0
    set ${rootname}Hour $hour
    set ${rootname}Month $todayMonth
    set ${rootname}Day $todayDay
    set ${rootname}Year $todayYear
}

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 
    APSDateTimeAdjEntry .endDate -parent $w \
      -yearVariable EndYear \
      -monthVariable EndMonth \
      -dayVariable EndDay \
      -hourVariable EndHour \
      -label "Ending date/time (year, month, day, hour):   " -defaultHour 24 
    
    SetDateTimeToToday -rootname Start -hour 0
    SetDateTimeToToday -rootname End  -hour 24
}


proc GetSelectedBPMList {args} {
    global BeamlineArray
    
    set SelectedBeamlineList ""
    foreach name [array name BeamlineArray] {
        global $BeamlineArray($name)
        if [set $BeamlineArray($name)] {
            set sector [scan $name %2d]
            set bpm ""
            if [regexp {BM} $name a b] {
                set bpm BM[format %.2d $sector]
            } elseif [regexp {ID} $name a b] {
                set bpm ID[format %.2d $sector]
            }
            if [string length $bpm] {
                lappend SelectedBeamlineList $bpm
            }
        }
    }
    if ![llength $SelectedBeamlineList] {
        return -code error "No beamline is selected!"
    }
    return [lsort $SelectedBeamlineList]
}

proc CalculateDownTime {args} {
    global StartYear StartMonth StartDay StartHour EndYear EndMonth EndDay EndHour
    global startTime0
    
    if [catch {GetSelectedBPMList} beamlineList] {
        SetStatus "$beamlineList"
        return
    }
    foreach nm {Start End} {
        set hourList [split [set ${nm}Hour] :]
        set hours [lindex $hourList 0]
        set minutes 0
        set seconds 0
        if [llength $hourList]>1 {
            set minutes [lindex $hourList 1]
        }
        if [llength $hourList]>2 {
            set seconds [lindex $hourList 2]
        }
        if [llength $hourList]>3 {
            return -code error "Invalid ${nm} hour - [set ${nm}Hour] provided."
        }
        set ${nm}Seconds [expr $hours * 3600 + $minutes * 60 + $seconds]
    }
    set starttime [expr [clock scan "$StartYear-$StartMonth-$StartDay"] + $StartSeconds]
    set endtime [expr [clock scan "$EndYear-$EndMonth-$EndDay"] + $EndSeconds]
    if {$starttime<$startTime0} {
        SetStatus "Unable to compute downtime earlier than 10/19/2004, please use BeamlineDownTimeCalculator to calculate down time before 10/19/2004"
        return
    }
    if {$endtime<$starttime} {
        SetStatus "Invalide data range given, the end date is earlier than the start date!"
        return
    }
    set tmpRoot /tmp/[APSTmpString]
    APSAddToTmpFileList -ID downtime -fileList "$tmpRoot.sdds $tmpRoot.print"
    SetStatus "Calculating...."
    if [catch {exec beamlineDownTime \
                 -directory=/home/helios/oagData/logonchange/EPS -rootname=EPS- \
                 -start=time=$starttime -end=time=$endtime \
                 -useDefault -beamline=[join $beamlineList ,] \
                 -controlName=edit=ai/EPS:/ei/:BLEPS:SPER/ $tmpRoot.sdds} result] {
        APSDeleteTmpFileList -ID downtime
        SetStatus "Error in calculating downtime: $result"
        return
    }
    SetStatus "Calculation done."
    if [catch {exec sddsprintout $tmpRoot.sdds $tmpRoot.print -par=* \
                 -col=Beamline -col=TotalDownTime,format=%12.3f \
                 -col=DownWithSchedule,format=%12.3f \
                 -col=DownWithBeam,format=%12.3f } result] {
        APSDeleteTmpFileList -ID downtime
        SetStatus "$result"
        return
    }
    APSFileDisplayWindow .[APSUniqueName printout] -fileName $tmpRoot.print \
      -width 100 -printCommand "enscript -r" -sddsExportableFile $tmpRoot.sdds \
      -deleteOnClose 1 -height 30 
   # APSDeleteTmpFileList -ID downtime
}
set startTime0 [clock scan "2004-10-19"]
set logDirectory /home/helios/oagData/logonchange/EPS
set status ""
set itemList {ID BM}
set sectorList ""
set missingList ""
if [catch {GetBeamlineList} result] {
    puts stderr $result
    exit
}

APSScrolledStatus .status -parent .userFrame -textVariable status -width 60 \
  -withButtons 1

APSSRSectorButtons .beamline -parent .userFrame -rootname beamline \
  -orientation horizontal -sectorList $sectorList \
  -label "Beamline" -description "Beamline selections" \
  -itemList $itemList -packOption "-side top" \
  -itemLabelList $itemList -sectorControl 1 \
  -missingList $missingList

MakeDateTimeFrame .time -parent .userFrame


APSButton .cal -parent .userFrame -text "Show Down Time" -command "CalculateDownTime"

APSGetVariableNameOfSRSectorButtons -sectorList $sectorList \
  -itemList $itemList -rootname beamline \
  -arrayName BeamlineArray

#unselect all
#foreach name [array name BeamlineArray] {
#    global $BeamlineArray($name)
#    set $BeamlineArray($name) 0
#}
