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

APSApplication . -name SRCorrectionDefaultConfigHistory -version $CVSRevisionAuthor \
  -overview "Prints out the orbit correction configurations that were linked to the\
   default configuration in the range of dates specified. "

set dataDir /home/helios/oagData/logDaemonData/UpdateSoftLinkAudit
#set dataDir /home/oxygen/SHANG/test/logd/UpdateSoftLinkAudit
set resDataDir /home/helios/oagData/logDaemonData

set statusText "Ready..."
APSScrolledStatus .status -parent .userFrame -textVariable statusText -width 60 \
  -contextHelp "Displays processing information." 
update

proc InitViewTime {args} {
    global buttList statusText fileList 
    global printoutString dataDir
    global StartYear StartMonth StartDay StartHour
    global EndYear EndMonth EndDay EndHour
    
    set type standard
    #three types: standard, DP, and RTFB
    APSParseArguments {type}
    set intervalString "$StartMonth/$StartDay/$StartYear $StartHour and $EndMonth/$EndDay/$EndYear $EndHour"
    set fileList ""
    set tempFile /tmp/[APSTmpString]
    set statusText "Working..."
    update
    
    #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!"
        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] {
        catch {eval exec sddscombine $processFileList -pipe=out -merge \
                 | sddsprocess -pipe -noWarnings \
                 -filter=column,Time,${lowLimit},${highLimit} \
                 | sddstimeconvert -pipe=in $tempFile \
                 -breakdown=col,Time,year=Year,month=Month,day=Day,hour=Hour,text=InstalTime \
             } result
    } else {
        set statusText "No data for the chosen range of time."
        bell
        return
    }
    
    if [catch {ViewTime [set tempFile]} result] {
        set statusText "$result"
    } else {
        set printoutString "Printout of the orbit correction configurations\
         that were linked to the default configuration between dates $intervalString.\n"

        MakeScrollList
    }
    set statusText "Done with the processing of the log files."
    update
}

proc DefineProcessList {} {
    global ordLogsList resDataDir dataDir statusText
    set dataList ""
    set i 1
    
    if [llength $ordLogsList] {
        foreach elem $ordLogsList {
            set tempFile.$i /tmp/[APSTmpString]
            if {[string compare $elem $resDataDir/UpdateSoftLinkAudit.log] == 0} {
                if [catch {exec sddsprocess $elem -pipe=out -noWarnings \
                             -define=parameter,Rows,n_rows,type=long \
                             -process=Time,first,TimeFirst \
                             -define=parameter,TimeLast,1e300,units=s \
                             | sddsconvert -pipe -retain=parameter,Rows,TimeFirst,TimeLast \
                             | sddscollapse -pipe -noWarnings \
                             | sddsprocess -pipe=in [set tempFile.$i] -noWarnings \
                             -print=column,FileName,$elem \
                         } result] {
                    set statusText $result
                } else {
                    lappend dataList [set tempFile.$i]
                    incr i
                }
            } else {
                if [catch {exec sddsprocess $elem -pipe=out -noWarnings \
                             -define=parameter,Rows,n_rows,type=long \
                             -process=Time,first,TimeFirst \
                             -process=Time,last,TimeLast \
                             | sddsconvert -pipe -retain=parameter,Rows,TimeFirst,TimeLast \
                             | sddscollapse -pipe -noWarnings \
                             | sddsprocess -pipe=in [set tempFile.$i] -noWarnings \
                             -print=column,FileName,$elem \
                         } result] {
                    set statusText "$result"
                } else {
                    lappend dataList [set tempFile.$i]
                    incr i
                }
            }
        }
        return $dataList
    }
}

proc ViewTime {maintempFile} {
    global statusText fileList corrtempFile planeSelection
    set corrtempFile /tmp/[APSTmpString]
    set matchString *${planeSelection}.default*

    if [catch {exec sddsprocess $maintempFile -pipe=out -noWarnings \
                 -match=column,Link=$matchString \
                 | sddssort -pipe=in $corrtempFile \
                 -column=InstalTime,increasing \
             } result] {
        set statusText "ViewTime: $result"
        update
    }
}

proc MakeScrollList {} {
    global fileList printoutString corrtempFile planeSelection
    set printFile /tmp/[APSTmpString]
    APSAddToTmpFileList -ID 1 -fileList "$printFile.dc $printFile.rtfb $printFile.dp $printFile.DP $printFile.RTFB $printFile.DC $printFile"
    if [catch {exec sddsprocess $corrtempFile $printFile.dc -nowarnings \
		   -match=col,Link=*orbitControllaw*,Link=*default,& 
	exec sddsprocess $corrtempFile $printFile.dcxr -nowarnings \
		   -match=col,Link=*orbitControllaw*,Link=*defaultXR,& 
        exec sddsprocess $corrtempFile $printFile.rtfb -nowarnings \
		   -match=col,Link=*rtfeedback*
	exec sddsprocess $corrtempFile $printFile.dpxr -nowarnings \
		   -match=col,Link=*defaultXRDP
	exec sddsprocess $corrtempFile $printFile.dp -nowarnings \
		   -match=col,Link=*defaultDP } result] {
        return -code error $result
    }
    set fid [open $printFile.title w]
    puts $fid "$printoutString"
    close $fid
    foreach type {dc dcxr rtfb dp dpxr} {
        set TYPE [string toupper $type]
        switch $type  {
            dc {
                set title "$planeSelection.default (Non-datapool Orbit Correction)"
            }
            dcxr {
                set title "$planeSelection.defaultXR (Non-datapool Orbit Correction with Xray bpms)"
            }
            dp {
                set title "$planeSelection.defaultDP (Datapool Orbit Correction)"
            }
            dpxr {
               set title "$planeSelection.defaultXRDP (Datapool Orbit Correction with Xray bpms)"
            }
            rtfb {
                set title "$planeSelection.default (RTFB)"
            }
        }
        eval exec sddsprintout $printFile.$type $printFile.$TYPE \
          {"-column=InstalTime,format=%25s,label=\"Installation Time\""}\
          {"-column=OldFile,format=%25s,label=\"Old Configuration\""}\
          {"-column=NewFile,format=%25s,label=\"New Configuration\""} \
          {"-title=\n$title"}
    }  
    
    exec cat $printFile.title $printFile.DC $printFile.DCXR $printFile.RTFB $printFile.DP $printFile.DPXR > $printFile
    APSFileDisplayWindow .[APSUniqueName review] -packOption "-side bottom" \
      -fileName $printFile -sddsExportableFile $corrtempFile -width 90 \
      -contextHelp "Displays a list of beam lines with existing data in\
         the selected time frame and a list of related steering start times."
}

# 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
}

MakeDateTimeFrame .timeFrame -parent .userFrame  

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

set f .userFrame.butframe.frame

set planeSelection h
APSRadioButtonFrame .plane -parent $f -label "Plane Selection" -variable planeSelection \
  -orientation horizontal -buttonList {"x/h" "y/v"} -valueList {h v} \
  -contextHelp "Provides a tool for the orbit plane selection." \
  -packOption "-side left"

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