#!/usr/bin/perl -T
# $Id: rig_template.cgi,v 1.7 2021/03/19 10:06:15 sqko Exp $
############################################################
############################################################
###                                                      ###
###   Originally designed by Soeren Koch                 ###
###                                                      ###
###   Impelemented by Soeren Koch                        ###
###                                                      ###
###   Copyright by Soeren Koch February 2015             ###
###                                                      ###
############################################################
############################################################

use strict;
use warnings;
use CGI qw(:standard :netscape);
use RFC::Main;
use RFC::Rig;
use RFC::RFCCGI qw(:cgi :html);
use RFC::Header;

my $acmode = get_cv('global','access_mode');
$acmode = 'celltest' unless ($acmode);

my $r = param('rig');
unless ($r)
{
    print header();
    print "No rig specified!\n";
    exit;
}
my $rig = RFC::Rig->new($r);

my $readmode = undef;
my $usermode = undef;
my $modifymode = undef;

my $equipid = $rig->get_cv('main','equipmentid');
$equipid = 0 unless ($equipid);
my $eqadr = get_cv('global','remote_equipment_database');
$eqadr = '' unless ($eqadr);
my $logaddr = get_cv('global','logbook_url');

my $allow = 0;
my $allow_log = 0;


if (!defined(param))
{
    &print_header("Please log in to the $name");
    print '<center>';
    RFC::RFCCGI::login();
    print '</center>';
    &print_end;
}
else
{
    my $allow = 0;
    my $auth = &get_cv('global','restrict_access_auth_only');
    if ($auth && $auth =~ /yes/)
    {
	$allow_log = 0;
        $allow = 0;
        my @authids = &get_cv('global','data_access_authorisationid');
        if (@authids)
	{
            my ($u,$p) = &RFC::RFCCGI::get_id();
            foreach my $id (@authids)
            {
		## Allow is user is authorised for at least one of the listed authorisations
                next if ($allow);
                eval {
                    $allow = SocketClient::socket_client('localhost',4042,'get_auth',$u,$id);
                };
                if ($@)
                {
                    ## Ignore if auth cache server is not running ##
                }
                next if ($allow);
                $allow = &RFC::Main::passwd_client('safety_auth',$u,$id);
                eval {
		    SocketClient::socket_client('localhost',4042,'set_auth',$u,$id,$allow);
                };
                if ($@)
                {
                    ## Ignore if auth cache server is not running ##
                }
            }
        }
    }
    else
    {
        $allow = 1;
	$allow_log = 1;
    }
    if (login_ok())
    { 
	$readmode = user_auth($acmode,'r');
	$usermode = user_auth($acmode,'c');
	$modifymode = user_auth($acmode,'m');
	if (RFC::RFCCGI::rig_mode())
	{
	    $readmode = 1;
	    $usermode = 1;
	    $modifymode = RFC::RFCCGI::rig_cert() unless ($modifymode);
	}
	unless (RFC::RFCCGI::rig_auth())
	{
	    $readmode = 0;
	    $usermode = 0;
	    $modifymode = 0;
	}
	else
        {
            $allow = 1;
        }
        &print_header("Main page for rig $rig",-onload=>'load_start()');
        print <<END;

<script language="javascript">

function load_start()
{
    load_info();
    load_log();
    load_data();
    load_error();
    load_isiv();
}

</script>

END


        unless ($allow)
        {
	    top_nav_bar_start;
	    top_no_button;
	    top_no_button;
	    top_no_button;
	    tab_newrow;
	    &js_back();
	    top_js_return('#006600','white');
	    top_no_button;
	    top_no_button;
	    top_no_button;
	    top_nav_bar_button('main.cgi','','','To menu','s4');
	    end_top_bar;
	    print h1({-class=>'Alert'},"You are not alowed to view rig ".$rig->name);
	    exit;
	}
        top_nav_bar_start;
        if ($allow_log || ($usermode && RFC::RFCCGI::rig_auth()))
        {
            if ($logaddr && $equipid)
            {
		top_nav_bar_button($logaddr,'','','Logbook for Rig '.$rig->name,'s3','rig,'.$rig->name.',1',"id,$equipid,1");
            }
            else
            {
                top_nav_bar_button('logbook.cgi','','','Rig '.$rig->name.' logbook','s3','rig,'.$rig->name.',1');
            }
	}
        else
        {
	    top_no_button;
	}
	if ($usermode)
	{
	    if ($rig->get_cv('userinterface','current'))
	    {
		top_nav_bar_button('start_new_test.cgi','','','Start a new test on rig'.$rig->name,'s0','rig,'.$rig->name.',1');
	    }
	    else
	    {
		top_nav_bar_button('start_new_electrode_test.cgi','','','Start a new test on rig'.$rig->name,'s0','rig,'.$rig->name.',1');
	    }
	}
	else
	{
	    top_no_button;
	}
	if ($usermode)
	{
	    top_nav_bar_button('setup_program.cgi','','','Program sequences','s3','rig,'.$rig->name.',1');
	}
	else
	{
	    top_no_button;
	}
	tab_newrow;
	if (get_CGI_value('action'))
	{
	    top_no_button;
	}
	else
	{
	    &js_back();
	    top_js_return('#006600','white');
	}
	if ($usermode)
	{
	    top_nav_bar_button('misc_conf.cgi','','','Miscellaneous setup','s1','rig,'.$rig->name.',1');
	}
	else
	{
	    my $server = get_cv('passwds','passwd_server');
	    my $taskid = &get_cv('safety_task_access','rig'.$rig->name); 
	    my @args = ('col,id,1');
	    foreach (split(/\s*\,\s*/,$taskid))
	    {
		push @args,'search_val,'.$_.',1';
	    }
	    if (CGI::https())
	    {
		top_nav_bar_button('https://'.$server.'/cgi-bin/search_safety_task.cgi','Search','dummy','Show nescesarry safety clerances for rig','s1',@args);
	    }
	    else
	    {
		top_nav_bar_button('http://'.$server.'/cgi-bin/search_safety_task.cgi','Search','dummy','Show nescesarry safety clerances for rig','s1',@args);
	    }
	}
        if (is_admin())
        {
	    top_nav_bar_button('rig_conf.cgi','','','Configuration','s0','rig,'.$rig->name.',1');
	}
        elsif ($allow_log || ($usermode && RFC::RFCCGI::rig_auth()))
        {
            if ($rig->is_iv)
            {
                top_no_button;
            }
            else
            {
                top_nav_bar_button('show_rig_values.cgi','','','Show current values','s2','rig,'.$rig->name.',1');
            }
        }
        else
        {
            top_no_button;
        }
        if ($rig->list_devices_control('PSU') || $rig->list_devices_control('analog'))
        {
            if ($readmode)
            {
                top_nav_bar_button('iv_setup.cgi','','','Setup i-V curve parameters','s3','rig,'.$rig->name.',1');
            }
            else
            {
                top_no_button;
            }
	}
        else
        {
            if ($modifymode || $usermode)
            {
                top_nav_bar_button('rig_setup.cgi','','','Rig '.$rig->name.' configuration','s2','rig,'.$rig->name.',1');
            }
            else
            {
                top_no_button;
            }
	}
	top_nav_bar_button('main.cgi','','','To menu','s4');
	end_top_bar;
	param(-name=>'action',-value=>'')  unless (defined(param('action')));
	$_ = param('action');
      CASE:
	{
	    ### Insert case statements ###
	    if (!$readmode) {&main_page;last CASE;};
	    &main_page;
	}
	print_end;
    }
    else 
    {
	&not_auth;
    }
}

$rig = undef;    
exit;



sub main_page
{
    print start_form(-name=>'data');
    print hidden(-name=>'isactive',-value=>1,-force=>1);
    print_hidden();
    print end_form();
    ################################################################
    ### Insert custom page design here                           ###
    ### This can be any combination of html and/or javascript    ###
    ### (javascript must of cause be contained in <script> tags) ###
    ################################################################









    #############################################################
    ## Form for submitting logbook entries                     ##
    ## Modify with classes and CSS to support desired layout   ##
    #############################################################
    if ($allow_log || ($usermode && RFC::RFCCGI::rig_auth()))
    {
	print start_form(-name=>'new_comment');
	&print_hidden_rig();
	print hidden(-name=>'eqid',-value=>$equipid,-force=>1);
	print hidden(-name=>'addr',-value=>$eqadr,-force=>1);
	&action('save_comment');
	print textarea(-name=>'comments',-value=>'',-force=>'1',-rows=>'3');
	print filefield(-name=>'filename');
	print button(-name=>'new_comm',-value=>'Add comment',-onclick=>'add_comment_file()');
	print end_form();
    }


    ######################################################################################
    ### Below here is a bunch of javascript functions for making interaction more easy ###
    ### It may be nescesarry to add to or edit the individual functions to correspond  ###
    ### with a custom user interface                                                   ###
    ######################################################################################
    my $user = get_user();

    print <<END;

<script>

/* Variables and functions for controling ivcurve popups etc */

window.onblur = set_inactive;
window.onfocus = set_active;
var ispopup = false;
var is_logged_in = true;
var username = '$user';

function check_status()
{
    raw_ajax('ajax.cgi','?action=is_logged_in&name='+username,set_status);
}

function set_status(res)
{
    var reg = /YES/;
    if (!reg.test(res))
    {   
	is_logged_in = false;
	document.logout.submit();
    }
}



function set_active()
{
    document.data.isactive.value = '1';
}

/* Ugly hack for IE wrongly triggering window onblur when selecting element inside page..... */

function ie_inactive()
{
    if (bIsMSIE && (active_element != document.activeElement)) {
	active_element = document.activeElement;
    }
    else 
    {	    
	document.data.isactive.value = '0';
    }
}

function set_inactive()
{
    if (navigator.appName == "Microsoft Internet Explorer") {
	active_element = document.activeElement;
	bIsMSIE = true;
	document.onfocusout = ie_inactive;
	return false;
    }
    ie_inactive();
}

/* end IE hack */

function iv_popup()
{
    if (document.data.isactive.value == 0 || ispopup == true)
    {
	return false;
    }
    ispopup = true;
    RFC_open('ivfig.cgi',510,380,100,400);
}

/* End iv popup functions */

function load_isiv()
{
    run_ajax('rig_ajax_run.cgi','&action=is_iv',set_iv);
    setTimeout("load_isiv()",10000);    
}

function set_iv(res)
{
    var btn = document.getElementById('iv_control_btn');
    if (btn == null)
	return false;
    if (res == 1)
    {
	btn.value = "Stop running iV curve";
	iv_popup();
    }
    else
    {
	btn.value = "Start iV curve";
	ispopup = false;
    }
}

function iv_control(btn)
{
    var val = btn.value;
    var reg = /Stop/;
    if (reg.test(val))
    {
	var ok = confirm("Stop running iV curve?");
	if (ok)
	{
	    run_ajax('rig_ajax_run.cgi','&action=stop_iv',set_temp_ok);
	}
    }
    else
    {
	run_ajax('rig_ajax_run.cgi','&action=start_iv',set_temp_ok);
    }
}


function set_PSU_go()
{
    var dev = document.PSU.device.value;
    var t = document.PSU.current.value;
    run_ajax('rig_ajax_run.cgi','&action=set_current&dev='+dev+'&current='+t,set_temp_ok);
}

function set_PSU_volt_go()
{
    var dev = document.PSU.device.value;
    var t = document.PSU.voltage.value;
    run_ajax('rig_ajax_run.cgi','&action=set_voltage&dev='+dev+'&voltage='+t,set_temp_ok);
}

function set_temp_go()
{
    var dev = document.temperature.device.value;
    var t = document.temperature.temp.value;
    var r = document.temperature.ramp.value;
    run_ajax('rig_ajax_run.cgi','&action=set_temp&dev='+dev+'&temp='+t+'&ramp='+r,set_temp_ok);
}

function set_relay_go()
{
    var dev = document.relay.device.value;
    var t = document.relay.status.value;
    run_ajax('rig_ajax_run.cgi','&action=set_relay&dev='+dev+'&status='+t,set_temp_ok);
}

function set_multiplex_go()
{
    var dev = document.multiplex.device.value;
    var g = document.multiplex.gas.value;
    run_ajax('rig_ajax_run.cgi','&action=set_multiplex&dev='+dev+'&gas='+g,set_temp_ok);
}


function set_gas_go()
{
    var dev = document.gas.device.value;
    var f = document.gas.flow.value;
    run_ajax('rig_ajax_run.cgi','&action=set_gas&dev='+dev+'&flow='+f,set_temp_ok);
}

function set_pid_go()
{
    var dev = document.pid.device.value;
    var f = document.pid.setpoint.value;
    run_ajax('rig_ajax_run.cgi','&action=set_pid&dev='+dev+'&setpoint='+f,set_temp_ok);
}

function set_imp_go()
{
    var server = document.is.server.value;
    var p = document.is.port.value;
    var u = document.is.impuser.value;
    var s = document.is.session.value;
    var cp = document.is.comp.value;
    run_ajax('rig_ajax_run.cgi','&action=set_imp&server='+server+'&port='+p+'&impuser='+u+'&session='+s+'&comp='+cp,set_temp_ok);
}

function set_temp_ok(t)
{
    alert(t);
    /* Sumbit the login info to reset logout timer */
    document.login_info.submit();
}

function set_log(t)
{
    document.proglog.proglog.value = t;
    document.proglog.proglog.scrollTop = document.proglog.proglog.scrollHeight;
}

function set_info(t)
{
    document.info.info.value = t;
}

function set_error(t)
{
    document.errorlog.errorlog.value = t;
}

function set_data(t)
{
    var arr = t.split("\\n");
    for (var i = 0; i < arr.length;i++)
    {
        if (arr[i] != null && arr[i] != "")
        {
            var item = arr[i].split("\\t");
            var element = document.getElementById(item[0]);
	    if (element != null)
	    {
		var str = element.innerHTML;
		var old = str.split(":");
		var newd = old[0]+': '+item[1];
		element.innerHTML = newd;
	    }
        }
    }
}


function load_data()
{
    if (is_logged_in)
    {
        run_ajax('UIdata.cgi','&action=data',set_data);
        setTimeout("load_data()",120000);
    }
}

function load_log()
{
    if (is_logged_in)
    {
	check_status();
	run_ajax('rig_ajax_run.cgi','&action=show_log',set_log);
	setTimeout("load_log()",50000);
    }
}

function load_info()
{
    if (is_logged_in)
    {
	run_ajax('rig_ajax_run.cgi','&action=show_info',set_info);
	setTimeout("load_info()",300000);
    }
}

function load_error()
{
    if (is_logged_in)
    {
	run_ajax('rig_ajax_run.cgi','&action=show_error',set_error);
	setTimeout("load_error()",300000);
    }
}


function add_comment_file()
{
    var txt = document.new_comment.comments.value;
    if (txt == null || txt == '')
    {
        alert('You have not entered any text to append');
        return false;
    }
    store_comment(txt);
}


function store_comment(str)
{
    var f = document.new_comment;
    var adr = f.addr.value;
    var id = f.eqid.value;
    if (id == 0 || adr == '')
    {
        document.new_comment.submit();
	return true;
    }
    if (confirm('Append this message to the public remote log book'))
    {
        if (document.new_comment.filename.files.length > 0)
        {
            remote_log_file(adr,id,str,load_ok,document.new_comment.filename.files[0]);
        }
        else
	{
            remote_log(adr,id,str,load_ok);
        }
        return true;
    }
    document.new_comment.submit();
}


function add_comment()
{
    var text = document.new_comment.comments.value;
    if (checkinput)
    {
	document.new_comment.comments.value = '';
	/* Translate all newlines to literal '\n' strings to make them
	    survive the XHTML transfer..... */
	text = text.replace(\/\\n\/mg,"\\\\n");
	run_ajax('rig_ajax_run.cgi','&action=add_info&comments='+text,set_info);
    }
}



</script>

END


}    

