#!/bin/bash

# To be executed at RASPs

source Commons.sh

whoami="Devices/RASPs/Operator/ControlScreen"

Charger="ssh golem@Charger"
Chamber="ssh -Y golem@Chamber bash --login -c" # Je tam na RASP:Chamber automaticky source ber.sh pres .bashrc
Dirigent="ssh golem@Dirigent"
Discharge="ssh  golem@Discharge bash --login -c"

xtermpars='-fn "-misc-fixed-medium-r-normal--20-*-*-*-*-*-iso8859-15" +sb -geometry 100x50+620+2 -fg yellow -bg blue '
drigentcommand='cd /home/svoboda/Dirigent/;echo AHOJ > nohup.out;nohup bash Dirigent.sh'


#MonitorDesktop=1
MonitorDesktop=0

function Dirigent()
{
     #RunApp@Desktop BasicManagement 3 0
     #RunApp@Desktop TokamakControllRoom 0 0
     #RunApp@Desktop xterm_controll 0 0
     #RunApp@Desktop ShotHomepage 2 1
     Monitor &
}





function TokamakControllRoom ()
{
    chromium-browser --new-window  https://golem.fjfi.cvut.cz/remote/control_room/?access_token=d0d7a97304f770040ce7782159b002c2\&identification=Master 
}

function ShotHomepage ()
{
    chromium-browser --new-window  https://golem.fjfi.cvut.cz/shots/0
}

function xterm_controll ()
{
    ssh -Y golem@Dg xterm
}

function RunApp@Desktop
{
    $1 &
    sleep 10
    WinID=`wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 |awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')|awk '{print $1}'`;
    wmctrl -i -r $WinID -t $2
    if [ $3 == 1 ]; then
        echo $WinID to full screen
        #wmctrl -i -r $WinID -b toggle,fullscreen
    fi
}


function KillAllApps
{
    killall chromium-browser 
    killall feh
    ssh -Y golem@Chamber "source Chamber.sh;KillFeed"
    
}

function ChargerOscWindow()
{
    #echo ":DISPLAY:SNAP? png"|netcat -w 1 192.168.2.78 5555|tail -c +12 >$SHML/ChargerOscScreenShot.png;
    #RefreshWindow ChargerOscScreenShot
    
    chromium-browser --new-window --app=http://192.168.2.78/auth/WebControl.html &
    
    #--force-device-scale-factor=0.20
    
    sleep 4
    WinID=`wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 |awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')|awk '{print $1}'`; echo $WinID > $SHM/Management/Production/"${FUNCNAME[0]}"WinID

    
}    




function StandardDASWindow()
{
    # 6 channels: 
    chromium-browser --new-window --app=http://192.168.2.143/Tektronix/#/client/c/Tek%20e*Scope &
    # 4 channels
    #chromium-browser --new-window --app=http://192.168.2.62/Tektronix/#/client/c/Tek%20e*Scope &
    
    sleep 4
    WinID=`wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 |awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')|awk '{print $1}'`; echo $WinID > $SHM/Management/Production/"${FUNCNAME[0]}"WinID


    #/usr/bin/python $SHM/Drivers/TektrMSO5/main56-a.py save_screenshot $SHML/StandardDASScreenShot.png 2>/dev/null
    #cutycapt --smooth --min-width=1600 --min-height=1200 --delay=500 --url=http://192.168.2.37/Tektronix/#/client/c/Tek%20e*Scope --out=google.png

    #cp $SHM0/DASs/TektrMSO56-a/ScreenShotAll.png $SHML/StandardDASScreenShot.png
    #RefreshWindow StandardDASScreenShot
    
    #chromium-browser http://192.168.2.78/auth/WebControl.html 
    
}

function MakeSessionChamber_p_T_Logbook()
{
gnuplot  -e "set xdata time;set timefmt '%H:%M';set format x '%H:%M';set xlabel 'Time [h:m]';set ylabel 'chamber pressure p_{ch} [mPa]';set xrange [*:*];set title 'Session chamber logbook';set yrange [0:30];set y2range [0:200];set y2tics 0, 20,200;set y2label'Chamber temperature T_{ch} [^o C]';set ytics nomirror;set terminal png;plot '$SHM/ChamberLog' using 1:2 title 'pressure' with lines axis x1y1,'$SHM/ChamberLog' using 1:3 title 'temperature' with lines axis x1y2" > $SHML/SessionChamber_p_T_Logbook.png

}


function SessionChamber_p_T_Logbook()
{

#MakeSessionChamber_p_T_Logbook

#        feh -x --scale-down --auto-zoom $SHML/${FUNCNAME[0]}.png &
        ssh -Y golem@Chamber "source Chamber.sh;ChamberGraph" &
        sleep 5
        WinID=`wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 |awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')|awk '{print $1}'`; echo $WinID > $SHM/Management/Production/"${FUNCNAME[0]}"WinID

    #RefreshWindow ${FUNCNAME[0]}
}

#in percent ...
HEADLINE=4
TOP=35
MIDDLE=35
BOTTOM=24
POMER=66

function GOLEMheadline()
{
    MakeGOLEMheadline
    
        feh -x --scale-down --auto-zoom $SHML/${FUNCNAME[0]}.png &
        Relax
        WinID=`wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 |awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')|awk '{print $1}'`; echo $WinID > $SHM/Management/Production/GOLEMheadlineWinID
    RefreshWindow GOLEMheadline
}


function MakeGOLEMheadline()
{
convert -size $((`cat $SHM/Management/Production/DesktopXsize`*1))x$((`cat $SHM/Management/Production/DesktopYsize`*$HEADLINE/100)) -background lightblue  -pointsize $((`cat $SHM/Management/Production/DesktopYsize`*$HEADLINE/100*6/10)) -fill black -gravity Center caption:"Tokamak GOLEM Shot No \#`cat $SHM/ActualSession/shot_no`" -flatten $SHML/GOLEMheadline.png

}

function GOLEMstatus()
{
MakeGOLEMstatus

        feh -x --scale-down --auto-zoom $SHML/${FUNCNAME[0]}.png &
        Relax
        WinID=`wmctrl -lp | grep $(xprop -root | grep _NET_ACTIVE_WINDOW | head -1 |awk '{print $5}' | sed 's/,//' | sed 's/^0x/0x0/')|awk '{print $1}'`; echo $WinID > $SHM/Management/Production/GOLEMstatusWinID

    RefreshWindow GOLEMstatus
}

function MakeGOLEMstatus()
{
convert -size $((`cat $SHM/Management/Production/DesktopXsize`*(100-$POMER)/100))x$((`cat $SHM/Management/Production/DesktopYsize`*$BOTTOM/100)) -background lightblue  -pointsize $((`cat $SHM/Management/Production/DesktopYsize`*1/40)) -fill black -gravity NorthWest caption:"p= `cat $SHM/ActualSession/SessionLogBook/ActualChamberPressuremPa` mPa\nT= `cat $SHM/ActualSession/SessionLogBook/ActualChamberTemperature` st C\n`date '+%H:%M:%S'`, Status:`cat $SHM/ActualSession/SessionLogBook/tokamak_state`" -flatten $SHML/GOLEMstatus.png
}



function RefreshWindow()
{
    if [ -f "$SHM/Management/Production/"$1"WinID" ]; then
        xdotool key --window `cat $SHM/Management/Production/"$1"WinID` r 
    fi
}

function GetDesktopResolution()
{
   DesktopXsize=`xrandr | head -n1 | cut -d, -f2 | cut -d" " -f3-5|awk '{print $1}'`;echo $DesktopXsize > $SHM/Management/Production/DesktopXsize
    DesktopYsize=`xrandr | head -n1 | cut -d, -f2 | cut -d" " -f3-5|awk '{print $3}'`;echo $DesktopYsize > $SHM/Management/Production/DesktopYsize
}
    
function Monitor()
{

# Initialization
    GetDesktopResolution
    
    sleep 5 # some problem with detection ??
    
    GetDesktopResolution

    
    #for i in GOLEMheadline ChargerOscScreenShot ; do 
    
    for i in ChargerOscWindow StandardDASWindow SessionChamber_p_T_Logbook GOLEMstatus GOLEMheadline; do
        echo Doing $i
        $i
    done
    
    Monitor2Idle
    
 
    while [ 1 ]; do
        echo Check the regime
        #if [ `cat $SHM/ActualSession/SessionLogBook/tokamak_state` = "idle" ]; then 
            MakeGOLEMheadline;RefreshWindow GOLEMheadline
            MakeGOLEMstatus;RefreshWindow GOLEMstatus
            #MakeSessionChamber_p_T_Logbook;RefreshWindow SessionChamber_p_T_Logbook
        
        #fi
        sleep 5
        if [ `cat $SHM/ActualSession/SessionLogBook/tokamak_state` = "preparing_discharge_BLA" ]; then DischargeRegime;fi

    done
}


function IdleRegime()
{
    echo Go to Idle regime
    Monitor2Idle
    #while [ `cat $SHM/ActualSession/SessionLogBook/tokamak_state` = "idle" ]; do
    while [ 1 ]; do
    
            MakeGOLEMheadline;RefreshWindow GOLEMheadline
            MakeGOLEMstatus;RefreshWindow GOLEMstatus
    
        sleep 5
    done    

}


function Monitor2Charging()
{
    SetWindowPos GOLEMheadline 0 0 2/3 1/10
    SetWindowPos ChargerOscScreenShot 0 1/5 2/3 4/5
    SetWindowPos StandardDASScreenShot 2/3 0 1/3 1/3
    SetWindowPos SessionChamber_p_T_Logbook 2/3 2/5 1/3 1/3
    SetWindowPos GOLEMstatus 2/3 8/10 1/3 1/10
}



function Monitor2Idle()
{
    SetWindowPos GOLEMheadline 0 0 100 $HEADLINE
    SetWindowPos ChargerOscWindow  0 $HEADLINE 100 $TOP
    SetWindowPos StandardDASWindow 0 $(($TOP+$HEADLINE)) 100 $MIDDLE
    
    SetWindowPos SessionChamber_p_T_Logbook 0 $(($HEADLINE+$TOP+$MIDDLE)) $POMER $BOTTOM
    
    
    SetWindowPos GOLEMstatus  $POMER $(($HEADLINE+$TOP+$MIDDLE)) $((100-$POMER)) $BOTTOM
}


function SetWindowPos ()
{

    DesktopXsize=`cat $SHM/Management/Production/DesktopXsize`
    DesktopYsize=`cat $SHM/Management/Production/DesktopYsize`
    wmctrl -i -r `cat $SHM/Management/Production/"$1"WinID` -e "0,$(($DesktopXsize*$2/100)),$(($DesktopYsize*$3/100)),$(($DesktopXsize*$4/100)),$(($DesktopYsize*$5/100))"
    wmctrl -i -r `cat $SHM/Management/Production/"$1"WinID` -t $MonitorDesktop
    # and reload window to resize image
    RefreshWindow $1
    
}






#sudo emacs -nw /home/pi/.config/lxsession/LXDE-pi/autostart
#@bash /home/pi/Operator.sh

function relay ()
{
    'Charger' "./Charger.sh -r RelayON 1" 2>/dev/null;
    sleep 2;
    'Charger' "./Charger.sh -r RelayOFF 3" 2>/dev/null
}




    

function AdvancedManagement ()
{
echo 'option add *font "Helvetica 25";\
wm title . Chamber@Operator
frame .title;\
frame .macros;\
frame .individuals;\
frame .relays_on;\
frame .relays_off;\
label .tit -text {Vacuum} -background blue;\
label .mac -text {Macros:} -background blue;\
label .indiv -text {Individuals:} -background blue;\
label .rel_on -text {Relays ON:} -background green;\
label .rel_off -text {Relays OF:} -background red;\
button .v_on -text "START" -command {exec '$Chamber' xtermPumpingON};\
button .v_off -text "END" -command {exec '$Chamber' xtermPumpingOFF};\
button .wg_test_h2 -text "WG H2 test " -command {exec '$Chamber' WGtestH2};\
button .wg_test_he -text "WG He test " -command {exec '$Chamber' WGtestHe};\
button .wg_calibr_h2 -text "WG H2 cal " -command {exec '$Chamber' xtermH2Calibration};\
button .rp_on -text "RotP ON" -command { exec '$Chamber' RotP_ON};\
button .rp_off -text "RotP OFF" -command {exec '$Chamber' RotP_OFF};\
button .tmps_on -text "TMPs ON" -command {exec '$Chamber' TMPs_ON};\
button .tmps_off -text "TMPs OFF" -command {exec '$Chamber' TMPs_OFF};\
button .vents_on -text "Vents ON" -command {exec '$Chamber' Vents_ON};\
button .vents_off -text "Vents OFF" -command {exec '$Chamber' Vents_OFF};\
button .temp -text "Temp ctrl" -command {exec chromium-browser 192.168.2.237 &};\
button .bak_on -text "Baking ON" -command {exec '$Chamber' Baking_ON};\
button .bak_off -text "Baking OFF" -command {exec '$Chamber' Baking_OFF};\
button .r1_on -text "1:S Vent" -background green -command {exec '$Chamber' Vent1ON};\
button .r1_off -text "1:S Vent" -background red -command {exec '$Chamber' Vent1OFF};\
button .r7_on -text "7:Rot" -background green -command {exec '$Chamber' RotPumpON};\
button .r7_off -text "7:Rot" -background red -command {exec '$Chamber' RotPumpOFF};\
pack .tit -in .title -side left;;\
pack .mac .v_on .v_off .rp_on .rp_off .temp .bak_on .bak_off .wg_test_h2 .wg_calibr_h2 .wg_test_he -in .macros -side left;\
pack .indiv .rp_on .rp_off .tmps_on .tmps_off .vents_on .vents_off -in .individuals -side left;\
pack .rel_on .r1_on .r7_on -in .relays_on -side left;\
pack .rel_off .r1_off .r7_off -in .relays_off -side left;\
pack .title;\
pack .macros;\
pack .individuals;\
pack .relays_on;\
pack .relays_off;\
'|wish
    }
    


function BasicManagement ()
{
    ssh -Y golem@Dg "cd /home/svoboda/Dirigent/RASPs;source Operator.sh; BasicManagementCore"
} 
 

