#!/usr/bin/perl -T
# $Id: start_new_test.cgi,v 1.34 2023/12/18 07:45:15 sqko Exp $
############################################################
############################################################
###                                                      ###
###   Originally designed by Soeren Koch                 ###
###                                                      ###
###   Impelemented by Soeren Koch                        ###
###                                                      ###
###   Copyright by Soeren Koch January 2011              ###
###                                                      ###
############################################################
############################################################

use strict;
use warnings;
use CGI qw(:standard :netscape);
use RFC::Main;
use RFC::Rig;
use RFC::RFCCGI qw(:cgi :html);
use RFC::Header;
use RFC::Device;
use LWP::UserAgent;
use URI::Escape;

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

my $account_reg = get_cv('global','account_number_regexp');
$account_reg = '\w+' unless ($account_reg);

if (!defined(param))
{
    print process('to_login.tt');
}
else
{
    if ($uid)
    {
        print process('main_nav.tt');
        $_ = param('action');
      CASE:
        {
	    ### Insert case statements ###
	    /^start_test$/ and do {&save; last CASE;};
	    ### Default response ####
    	    &insert_data_form_template;
        }
        print process('end_html.tt');
    }
    else 
    {
        print process('not_auth.tt');
    }
}
exit;

sub insert_data_form_template()
{
    my %data = ();
    my $account_reg = get_cv('global','account_number_regexp');
    $account_reg = '\w+' unless ($account_reg);
    $data{'account_reg'} = $account_reg;
    $account_reg =~ s/\\/\\\\/g;
    $data{'account_reg_display'} = $account_reg;
    my $ok = 1;
    my $data = RFC::Cache->new();
    foreach ($rig->list_devices('templog'))
    {
	eval {
	    my $dev = $rig->get_device('templog',$_);
	    my $temp = $dev->read($data);
	    $ok = 0 if ($temp > 50 && $temp < 2000);
	};
    }
    $data{'ok'} = $ok;
    $data{'project'} = &get_cv('global','project_number_validate_url');
    $data{'warning_mails'} = scalar($rig->get_cv('main','warning_mails'));    
    $data{'email'} = &RFC::Main::passwd_client('email',&get_user());
    print process('start_new_test.tt',&get_template_data_ref(\%data));
}



sub remote_log($)
{
    my $msg = shift;
    my $encode = uri_escape($msg);
    my $eqid = $rig->get_cv('main','equipmentid');
    $eqid = 0 unless ($eqid);
    my $eqadr = get_cv('global','remote_equipment_database');
    return unless ($eqid && $eqadr);
    my $ua = LWP::UserAgent->new();
    $ua->timeout(60);
    my $url = $eqadr;
    my $query = '?name='.&get_user().'&pass='.&get_pass().'&action=new_maint_log&type=Riglog&equipid='.$eqid.'&description='.$encode;
    my $request = new HTTP::Request('GET',$url.$query);
    my $response = $ua->request($request);
    return if ($response->is_success);
    &errorlog("Could not append mesage to remote message log for rig $rig!");
}

sub save()
{
    my $id = &get_CGI_value('id');
    my $name1 = &get_CGI_value('name1');
    my $name2 = &get_CGI_value('name2');
    my $name3 = &get_CGI_value('name3');
    my $akk = &get_CGI_value('anode_current_collector');
    my $kkk = &get_CGI_value('cathode_current_collector');
    my $ah = &get_CGI_value('anode_house');
    my $kh = &get_CGI_value('cathode_house');
    my $gak = &get_CGI_value('anode_glass');
    my $gkk = &get_CGI_value('cathode_glass');
    my $pp = &get_CGI_value('sample_info');
    my $tp = &get_CGI_value('testplan');
    my $comm = &get_CGI_value('comments');
    my $project = &get_CGI_value('project');
    my $ok = 1;
    if ($account_reg)
    {
	$ok = 0 unless ($project && $project =~ /$account_reg/);
    }
    $ok = 0 unless ($id);
    $ok = 0 unless ($akk);
    $ok = 0 unless ($ah);
    $ok = 0 unless ($akk);
    $ok = 0 unless ($kh);
    $ok = 0 unless ($pp);
    $ok = 0 unless ($tp);
    if ($ok)
    {
	my $str = "Test house                  : $ah - $kh\n";
	$str .= "Alternate test numbers      : $name1\n";
	$str .= "                            : $name2\n";
	$str .= "                            : $name3\n\n";
	$str .= "Sample number               : $id\n";
	$str .= "Anode current collector     : $akk\n";
	$str .= "Cathode current collector   : $kkk\n";
	$str .= "Sealant on anode side       : $gak\n";
	$str .= "Sealant on cathode          : $gkk\n\n";
	$pp =~ s/\n/ /g;
	$str .= "Sample information          : $pp\n\n";
	$tp =~ s/\n/ /g;
	$str .= "Test plan                   : $tp\n\n";
	$str .= "Additional test information : $comm\n\n";
        #### Report script strings ####
	$str .= '#############################################################'."\n";
	$str .= '####################### Report information ##################'."\n";
	$str .= '#############################################################'."\n";
        $pp =~ s/\n/ /g;
        $str .= 'KEYWORDS # '.$pp."\n";
        $tp =~ s/\n/ /g;
        $str .= 'TESTPLAN # '.$tp."\n";
	$project =~ s/\n/ /g;
        $str .= 'PROJECT # '.$project."\n";
	$str .= '#############################################################'."\n";
	$str .= '####################### END information    ##################'."\n";
	$str .= '#############################################################'."\n";
	$str .= "\n";
	eval 
	{
	    my $msg = $str;
	    my $res = $rig->inc_test($str,get_user());
	    my $time = localtime();
	    my $inf = $RFC::Header::homedir.'info_table.txt';
	    my $str = "$time  ".$rig->name.'test'.$res."  $id  $name1  $name2  $name3\n";
	    ### Remove hash marks from string (as they messes up the search system)
	    $str =~ s/\#/\_/g;
	    open INF , '>>' , $inf or die "Could not open info file $inf!";
	    print INF $str;
	    close INF;
	    print center(h1("New test started for rig ".$rig->name.", current test is now $res!"));
	    &remote_log('New test started: '.$msg.$str);
	};
	if ($@)
	{
	    &errorlog("New test not started correctly on ".$rig->name.", Error: $@");
	    &print_error();
	}
    }
    else
    {
        print center(h1({-class=>'Alert'},"Not all required fields contained information!"));
    }
}

sub insert_data_form
{
    print header(-charset=>'utf-8');
    my $ok = 1;
    my $data = RFC::Cache->new();
    foreach ($rig->list_devices('templog'))
    {
	my $dev = $rig->get_device('templog',$_);
	my $temp = $dev->read($data);
	$ok = 0 if ($temp > 50 && $temp < 2000);
    }
    unless ($ok)
    {
	print "\n\n<script lanuage='javascript'>\n";
	print "function alert_test() {\n";
	print "    if(confirm('Warning! Temperature is above 50C, a test is likely already running!\\n Continue with new test?')) {\n";
	print "        return true;\n";
	print "    }\n";
	print "    else {\n";
	print "        back();\n";
	print "        return false;\n";
	print "    }\n";
	print "}\n";
	print "</script>\n\n";
	print RFC_start_html(-title=>"Start new test on rig ".$rig->name, -style=>{src=>'/celltest/RFCcontrol.css'},-onload=>'alert_test()');
    }
    else
    {
	print RFC_start_html(-title=>"Start new test on rig ".$rig->name, -style=>{src=>'/celltest/RFCcontrol.css'});
    }
    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_nav_bar_button('rig_main.cgi','','','To rig'.$rig->name.' main page','s3','rig,'.$rig->name.',1');
    top_nav_bar_button('main.cgi','','','To menu','s4');
    end_top_bar;
    my $test = $rig->session;
    print center(h1("Current test for rig ".$rig->name." is $test"));
    print '<center>';
    print '<table border=0 cellspacing=5 cellpadding=0 style="width:100%"><tr height=1>';
    print '<td width="10%"></td>';
    print '<td width="20%"></td>';
    print '<td width="20%"></td>';
    print '<td width="20%"></td>';
    print '<td width="20%"></td>';
    print '<td width="10%"></td>';
    print '</tr>';
    RFC::RFCCGI::print_js_validate('sofc','id','project;"'.$account_reg.'";Account number not in correct format','anode_house','cathode_house','anode_current_collector','cathode_current_collector','sample_info','testplan');
    unless ($ok)
    {
	print "\n\n<script lanuage='javascript'>\n";
	print "function checki() {\n";
	print "   var test = alert_test();\n";
	print "   var input = checkinput();\n";
	print "   if (test && input) {\n";
	print "       return true;\n";
	print "   }\n";
	print "   else {\n";
	print "       return false;\n";
	print "   }\n";
	print "}\n";
	print "</script>\n\n";
	print start_form(-name=>'sofc',-class=>"form",-onsubmit=>'return checki()');
    }
    else
    {
	print start_form(-name=>'sofc',-class=>"form",-onsubmit=>'return checkinput()');
    }
    &print_hidden_rig;
    &action('start_test');
    #### Inputside #####
    print '<tr><td colspan=6 class="heading">';
    print "New test information:";
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Sample number (*):';
    print '</th><td>';
    print textfield(-name=>'id',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><th>';
    print 'Project number (*):';
    print '</th><td>';
    my $validate = &get_cv('global','project_number_validate_url');
    if ($validate)
    {
        my $q = '&name='.param('name').'&pass='.param('pass');
        print textfield(-name=>'project',-value=>'',-force=>'1',-class=>'textfield',-onchange=>"raw_ajax('$validate'+this.value,'$q',ajax_alert)");
    }
    else
    {
        print textfield(-name=>'project',-value=>'',-force=>'1',-class=>'textfield');
    }
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Other test numbers:';
    print '</th><td>';
    print textfield(-name=>'name1',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><td>';
    print textfield(-name=>'name2',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><td>';
    print textfield(-name=>'name3',-value=>'',-force=>'1',-class=>'textfield');
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Anode house (*):';
    print '</th><td>';
    print textfield(-name=>'anode_house',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><th>';
    print 'Cathode house (*):';
    print '</th><td>';
    print textfield(-name=>'cathode_house',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><td>';
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Anode curent collector (*):';
    print '</th><td>';
    print textfield(-name=>'anode_current_collector',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><th>';
    print 'Cathode current collector (*):';
    print '</th><td>';
    print textfield(-name=>'cathode_current_collector',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><td>';
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Sealing on anode:';
    print '</th><td>';
    print textfield(-name=>'anode_glass',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><th>';
    print 'Sealing on cathode:';
    print '</th><td>';
    print textfield(-name=>'cathode_glass',-value=>'',-force=>'1',-class=>'textfield');
    print '</td><td>';
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Sample preparation information (*):';
    print '</th><td colspan=3>';
    print textarea(-name=>'sample_info',-value=>'',-force=>'1',-rows=>'3',-class=>'textfield');
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Test plan (*):';
    print '</th><td colspan=3>';
    print textarea(-name=>'testplan',-value=>'',-force=>'1',-rows=>'3',-class=>'textfield');
    print '</td></tr>';
    print '<tr><td></td><th>';
    print 'Further comments:';
    print '</th><td colspan=3>';
    print textarea(-name=>'comments',-value=>'',-force=>'1',-rows=>'5',-class=>'textfield');
    print '</td></tr>';
    print '<tr><td colspan=2></td><td colspan=2>';
    print button(-name=>'dummy',-value=>'Start new test',-class=>'s0',-onclick=>'start_test()');
    print '</td></tr>';
    print submit(-name=>'test',-class=>'hidden');
    print end_form();
    print '</table>';
    my $r = $rig->name;
    print <<END;

<script lanuage=javascript>
function start_test()
{
    if (confirm('Start new test for rig $r?'))
    {
	document.sofc.test.click();
    }
}
</script>
END
}    

