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


# it converts beamline schedule, computer usage and downtime, creates reports

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.9 $ \$Author: shang $"

APSApplication . -name BeamlineUsageReport -version $CVSRevisionAuthor \
      -overview {This application converts beamline schedule, computer usage and downtime, creates reports .}

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

proc ShowConversionErrors {args} {
    global beamlineList runName
    global mainDir
    
    set opt ""
    if ![llength $beamlineList] {
        SetStatus "No beamline selected for view converting result."
        return
    }
    set beamList ""
    foreach beam $beamlineList {
        global $beam
        if [set $beam] {
            if ![string length $opt] {
                set opt -match=par,Beamline=$beam
            } else {
                append opt ,Beamline=$beam,|
            }
            lappend beamList $beam
        }
    }
   
    set tmpRoot /tmp/[APSTmpString]
    
    if [catch {exec sddsprocess $mainDir/$runName/$runName.error -nowarnings $opt -pipe=out  \
                 | sddsprocess -pipe=in $tmpRoot.error "-define=par,rows,n_rows,type=long" \
                 -filter=par,rows,0,0,! -nowarnings } result] {
        return -code error $result
    }
    if [catch {exec sddsprocess $mainDir/$runName/$runName.warning -nowarnings $opt -pipe=out  \
                 | sddsprocess -pipe=in $tmpRoot.warning "-define=par,rows,n_rows,type=long" \
                 -filter=par,rows,0,0,! -nowarnings } result] {
        return -code error $result
    }
    set npages [exec sdds2stream -npages=bare $tmpRoot.error]
    if !$npages {
        SetStatus "No errors found in $runName schedule conversion for beamline [join $beamList ,]."
        return
    } else {
        if [catch {exec sddsprintout $tmpRoot.error $tmpRoot.error.printout "-title=Errors found in converting $runName schedules." \
                     -par=Beamline -col=Station -col=StartDate -col=EndDate -col=Shifts,format=%.1f -col=AvailableShifts,format=%.1f \
                 } result] {
            return -code error $result
        }
        APSFileDisplayWindow .error -fileName $tmpRoot.error.printout -width 100 -printCommand "enscript -r"
    }
    set npages [exec sdds2stream -npages=bar $tmpRoot.warning]
    if $npages {
        
    }
}

set debug 1
proc ConvertBeamlineSchedule {args} {
    global beamlineList runName scheduleDir updateSchedule debug

    set beamList ""
    foreach beam $beamlineList {
        global $beam
        if [set $beam] {
            lappend beamList $beam
            if $updateSchedule {
                SetStatus "Copy schedule $runName-$beam.csv ..."
                if ![file exist $scheduleDir/$runName/$runName-$beam.csv] {
                    SetStatus "$runName-$beam.csv does not exist, please check or unselect $beam!"
                    return
                }
                exec cp $scheduleDir/$runName/$runName-$beam.csv \
                  /home/helios/oagData/sr/beamlineDownTime/beamlineSchedules/$runName/$runName-$beam.csv 
                if {$beam=="11BM"} {
                    exec cp $scheduleDir/$runName/11BMproposallist.csv \
                      /home/helios/oagData/sr/beamlineDownTime/beamlineSchedules/$runName/11BMproposallist.csv
                }
                if {$beam=="31ID"} {
                    exec cp $scheduleDir/$runName/$runName-31IDschedule.csv \
                      /home/helios/oagData/sr/beamlineDownTime/beamlineSchedules/$runName/$runName-31IDschedule.csv 
                }
            }
        }
    }
    if ![llength $beamList] {
        SetStatus "no beamline selected."
        return
    }
    SetStatus "Convert [join $beamList ,] schedules for $runName..."
    SetStatus "It may take several minutes, please wait ..."
    update
    if !$debug {
        if [catch {exec /home/helios/oagData/sr/beamlineDownTime/beamlineSchedules/convertSchedule -verbose 1 -runName $runName \
                    -beamlineList $beamList -verbose 0} result] {
            SetStatus $result
            return -code error $result
        }
    } else {
        
        foreach beam $beamList {
            SetStatus "converting $beam ..."
            update
            if [catch {exec /home/helios/oagData/sr/beamlineDownTime/beamlineSchedules/convertSchedule -verbose 1 -runName $runName \
                         -beamlineList $beam -verbose 0} result] {
                SetStatus "Error in converting $beam :$result"
                SetStatus "Please check the schedule."
                return
             }
        }
    }
    SetStatus "done."
}

proc ConvertLogData {args} {

    global mainDir runName
    set oldDir [pwd]
    cd $mainDir/$runName
    if ![file exist ../beamlineSchedules/$runName/$runName.sdds] {
        SetStatus "The schedule for $runName was not converted yet, please convert the schedule for $runName first."
        return
    }
    catch {exec cp ../beamlineSchedules/$runName/$runName.sdds schedule.sdds}
    set tmpRoot /tmp/[APSTmpString]
    if [catch {exec sddsprocess /home/helios/oagData/sr/beamlineDownTime/APS_schedule.sdds -match=col,RunName=$runName $tmpRoot.1 } result] {
        return -code error $result
    }
    foreach nm {Start End} {
        foreach name {Year Month Day} {
            gloabl ${nm}$name
            set ${nm}$name [exec sdds2stream -col=${nm}$name $tmpRoot.1]
        }
    }
    set cols [exec sddsquery -col schedule.sdds | grep PA*]
    set update 1
    set endTime [clock scan $EndMonth/$EndDay/$EndYear]
    foreach col $cols {
        if ![file exist $col.sdds] {
            set update 0
            break
        }
        set mtime [file mtime $col.sdds]
        if {$mtime<$endTime} {
            set update 0
            break
        }
    }
    if $update {
        SetStatus "The log data has been updated already."
        cd $oldDir
        return
    }
    SetStatus "Converting log data for $runName, please wait ..."
    update
    catch {exec prepare_pss_logdata schedule.sdds .  -startTime=year=$StartYear,month=$StartMonth,day=$StartDay \
             -endTime=year=$EndYear,month=$EndMonth,day=$EndDay }
    SetStatus "done."
    cd $oldDir
}

proc ComputeDownTime {args} {
   
    global mainDir StartYear StartMonth StartDay EndYear EndMonth EndDay runName
    set oldDir [pwd]
    cd $mainDir/$runName
    ConvertLogData -runName $runName
    SetStatus "Compute downtime for $runName ..."
    catch {exec compute_station_downtime -dataDir=. downtime.sdds \
             -startTime=year=$StartYear,month=$StartMonth,day=$StartDay \
             -endTime=year=$EndYear,month=$EndMonth,day=$EndDay  -scheduleData=schedule.sdds }
    SetStatus "compute station downtime done."
    SetStatus "Generating station usage webpage..."
    catch {exec $mainDir/scripts/createHtml -runName $runName}
    SetStatus "done."
    cd $oldDir
}

proc ComputeBeamlineUsage {args} {
    set year 2009
    APSParseArguments {year}
    global mainDir
    SetStatus "compute beamline usage for year $year..."
    update
    set lastYear [expr $year -1]
    set runList [list ${lastYear}-Run3 $year-Run1 $year-Run2]
    foreach run $runList {
        if ![file exist $mainDir/$run/downtime.sdds] {
            SetStatus "The downtime for $run has not been computed yet. compute it first!"
            return
        }
    }
    if [catch {exec $mainDir/scripts/beamlineUsageReport -year $year -recompute 1 } result] {
        SetStatus $result
        return
    }
    SetStatus "done."
}

set year 2009
proc GenerateSummaryReport {args} {
    global mainDir year
    SetStatus "Generating summary report for $year ..."
    update
    exec $mainDir/generateSummaryPage -year $year
    SetStatus "done."
}

proc GenerateOracleReport {args} {
    
    global runName mainDir
    SetStatus "Generating oracle report for $runName ..."
    update
    exec $mainDir/generateReport -runName $runName
    SetStatus "done."
}
set mainDir /home/helios/oagData/sr/beamlineDownTime/beamlineSchedules
APSScrolledStatus .status -parent .userFrame -textVariable status -width 60 \
  -withButtons 1

set scheduleDir /home/oxygen25/RT
set updateSchedule 0
set runName 2008-Run3
set runList [exec sddsprocess /home/helios/oagData/sr/beamlineDownTime/APS_schedule.sdds -pipe=out \
    -filter=col,StartYear,2008,2500 | sdds2stream -pipe -col=RunName]
APSLabeledEntry .dir -parent .userFrame -label "Schedule directory:" -width 80 -textVariable scheduleDir
APSRadioButtonFrame .update -parent .userFrame -label "Update schedule?" -buttonList {Yes No} \
  -valueList {1 0} -variable updateSchedule -orientation horizontal \
  -contextHelp "Choose yes if the schedule has been updated or it is the first time to convert, otherwise select no"
APSRadioButtonFrame .first -parent .userFrame -label "Debug?" -buttonList {Yes No} -valueList {1 0} \
  -variable debug -orientation horizontal 
APSRadioButtonFrame .run -parent .userFrame -label "APS Run:" -orientation horizontal  \
  -buttonList $runList -variable runName -valueList $runList
set beamlineList [exec sdds2stream -col=Beamline /home/helios/oagData/sr/beamlineDownTime/beamlineSchedules/beamline.sdds]
foreach beam $beamlineList {
    set $beam 1
}
APSCheckButtonFrame .sel -parent .userFrame -label "Select beamlines:"  \
    -buttonList $beamlineList -variableList $beamlineList -allNone 1  \
    -limitPerRow 5

#MakeDateTimeFrame .time -parent .userFrame


APSButton .convert -parent .userFrame -text "ConvertSchedule" -command "ConvertBeamlineSchedule"
APSButton .show -parent .userFrame -text "Display Convert Errors" -command "ShowConversionErrors"
APSButton .report -parent .userFrame -text "Generate Summary Report" -command "GenerateSummaryReport"
APSButton .oracle -parent .userFrame -text "Generate Oracle Report" -command "GenerateOracleReport"
APSButton .downtime -parent .userFrame -text "Compute DownTime" -command "ComputeDownTime"
APSButton .usage -parent .userFrame -text "Compute Beamline Usage" -command "ComputeBeamlineUsage"

