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

#first version, 2014/1/9 shang for manually collecting ITS PC gun conditioning data.

set CVSRevisionAuthor "\$Revision: 1.0 $ \$Author: shang $"
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)]
APSStandardSetup

proc SetStatus {text} {
    global status
    set status "$text"
    update
}

proc CollectData {args} {
    global monFile dataDir comment
    if ![string length $comment] {
        SetStatus "Please enter description!"
        return
    }
    set tmpRoot /tmp/[APSTmpString]
    SetStatus "collecting data..."
    set file $dataDir/[clock format [clock seconds] -format %Y-%j-%m%d].sdds
    
    if [catch {exec sddsmonitor  $monFile $tmpRoot.1 -step=1 -oncaerror=usezero -pend=10 } result] {
        SetStatus "Error reading pvs: $result"
        return
    }
    if [catch {exec sddstimeconvert $tmpRoot.1 -pipe=out -breakdown=col,Time,text=DateTime  \
                 | sddsprocess -pipe  "-print=col,Description,[APSMakeSafeQualifierString $comment]" \
                 | sddsconvert -pipe -del=col,Step,CAerrors,Time,TimeOfDay,DayOfMonth  \
                 | sddssortcolumn -pipe=in $tmpRoot.2 -sortList=DateTime,Description,* } result] {
        return -code error "Error print comment parameter: $result"
    }
    if ![file exist $file] {
        exec cp $tmpRoot.2 $file
    } else {
        exec cp $file $tmpRoot.3
        if [catch {exec sddscombine $tmpRoot.2 $tmpRoot.3 $file -over -merge } result] {
            return -code error "$result"
        }
    }
    file delete -force "$tmpRoot.1 $tmpRoot.2 $tmpRoot.3"
    SetStatus "done."

}


proc PrintSelectFile {args} {
    global selectFile dataDir Checked printAll
    cd $dataDir
    
    if $printAll {
        exec sddsedit $selectFile
        return
    }
    set cols [join [exec sddsquery -col $selectFile]]
    foreach col $cols {
        global $col
        set $col 0
    }
    set DateTime 1
    set Description 1
    set checked ""
    APSDialogBox .check -name "Select PV name to review." -modal 0 \
      -okCommand "set Checked 1" -cancelCommand "set Checked 0"
    APSCheckButtonFrame .checkpv -parent .check.userFrame -label "" \
      -buttonList $cols -variableList $cols -orientation vertical
    
    tkwait variable Checked
    if !$Checked {
        destroy .check
        return
    }
    set opt ""

    foreach col $cols {
        global $col.format
        if [set $col] {
            if {$col=="DateTime"} {
                lappend opt -col=$col,format=%25s
            } elseif {$col=="Description"} {
               # lappend opt -col=$col,format=%25s
            } else {
                lappend opt -col=$col,format=[set ${col}.format]
            }
        }
    }
    if [lsearch $cols "Description"]>=0 {
        lappend opt -col=Description,format=%-25s
    }
    if ![llength $opt] {
        SetStatus "No PVs selected."
        return
    }
    set tmpFile /tmp/[APSTmpString]
    if [catch {eval exec sddsprintout $selectFile $opt $tmpFile -width=200} result] {
        return -code error $result
    }
    APSFileDisplayWindow  [APSUniqueName .] -fileName $tmpFile \
      -width 200 -printCommand "enscript -r" 
}

proc PrintData {args} {
    set all 0
    APSParseArguments {all}

    global dataDir selectFile printAll
    set printAll $all
    cd $dataDir
    set files [lsort -decreasing [glob *.sdds]]
    set selectFile ""
    APSScrolledListWindow .its -name "Select file for view" \
	-label "Select File for view." -callback PrintSelectFile \
	-itemList $files  -selectionVar selectFile
    tkwait variable selectFile
    if ![llength $selectFile] {
        SetStatus "no file chosen."
        return
    }
    return
}

proc AddNewPV {args} {
    global newPV monFile 
    
    set pvList ""
    foreach pv $newPV {
        if [catch {exec cavget -list=$pv -printErrors} result] {
            SetStatus "Error: $result"
            SetStatus "$pv was not added."
            continue
        }
        set tmpRoot /tmp/[APSTmpString]
        if [catch {exec sddsprocess $monFile -nowarnings -match=col,ControlName=$pv $tmpRoot.1} result] {
            return -code error $result
        }
        set rows [exec sdds2stream $tmpRoot.1 -rows=bar]
        exec rm $tmpRoot.1
        if $rows {
            SetStatus "$pv is already included in the monitor file."
            continue
        }
        lappend pvList $pv
        global $pv.format
        set $pv.format %s
    }
    if ![llength $pvList] {
        SetStatus "no new pvs added."
        return
    }
    set file [file readlink $monFile]
    set dir [file dir $monFile]
    set oldDir [pwd]
    cd $dir
    set newName [APSNextGenerationedName -directory $dir -name [file tail $monFile]-0000 -separator - -newFile 1]
    if [catch {exec sddsmakedataset -pipe=out -col=ControlName,type=string -data=[join $pvList ,] \
             | sddsprocess -pipe=in $tmpRoot "-print=col,Format,%f"} result] {
        return -code error $result
    }
    if [catch {exec sddscombine $monFile $tmpRoot -merge -pipe=out \
             | sddssort -pipe=in -col=ControlName -unique $newName } result] {
        return -code error $result
    }
    exec rm $tmpRoot
    exec rm $monFile
    exec ln -s $newName PCGunConditioning.mon
    cd $oldDir
    SetStatus "$newPV is added to monitor file."
}

set monFile /home/helios/oagData/ITS/inputFiles/PCGunConditioning.mon
set pvs [exec sdds2stream $monFile -col=ControlName]
set formats [exec sdds2stream $monFile -col=Format]
foreach pv $pvs format $formats {
    set $pv.format $format
}

set dataDir /home/helios/oagData/ITS/PCG_Conditioning

set status ""
set newPV ""
APSApplication . -name AcquireITSPCGunConditioningData -version $CVSRevisionAuthor \
    -overview {This utility is for acquring ITS PC Gun Conditioning data}
APSScrolledStatus .status  -parent .userFrame  -textVariable status -width 100 \
  -height 4 -withButtons 1 -packOption "-fill x"

set comment ""
APSLabeledEntry .comment -parent .userFrame -label "Description: " -textVariable comment -width 80 -packOption "-fill x -expand true"
APSLabeledEntry .newpv -parent .userFrame -label "New PV names (separate by space):" -textVariable newPV -width 80 -contextHelp "add new pv to the monitor file." \
-packOption "-fill x -expand true"

APSButton .collect -parent .userFrame -text "Collect Data" -command "CollectData" -contextHelp "collect PC conditioning data."
APSButton .plot2 -parent .userFrame -text "Print Selected Data" -command "PrintData -all 0" -contextHelp "printout selected pvs of selected file."
APSButton .plot3 -parent .userFrame -text "Print All Data" -command "PrintData -all 1" -contextHelp "use sddsedit to view all pvs of selected file."
APSButton .addpv -parent .userFrame -text "Add New PV" -command "AddNewPV" -contextHelp "add new pv to monitor file."

set figureDir $env(HOME)
