#!/usr/bin/perl -T
# $Id: multi_iv.cgi,v 1.14 2023/05/17 08:15:04 sqko Exp $
use strict;
use warnings;
use Sys::Hostname;
#use Impedance::Header;
#use Impedance::Model;
#use Impedance::IMPCGI qw(:html :cgi);
use RFC::Main;
use RFC::Header;
use RFC::RFCCGI  qw(:html :cgi);
use CGI qw(:standard :netscape);
use SemaforeFile;
use File::stat;
use ElchemeaConfig;


if (!defined(param))
{
    print process('to_login.tt');
    exit;
}
my ($u,$p) = &RFC::RFCCGI::get_id();
my $allow = &RFC::RFCCGI::rig_data_access_allow();

unless ($allow)
{
    print process('not_auth.tt');
    exit;
}

my $plotmode = param('plotmode');
$plotmode = 'Nyquist' unless ($plotmode);


print process('main_nav.tt');
print center(button(-name=>'eps',-value=>'save postscript image',-class=>'s3',-onclick=>'save_ps()'));

$_ = param('action');
 CASE:
{
    ### Insert case statements ###
    ### Default response ####
    if ($_ =~ /Load/i)
    {
	&main_form(param('filename'));
    }
    else
    {
	&main_form;
	my $action = '';
	$action = 'setTimeout("set_filelist()",100);' if (param('session'));
	print <<END;
	
<script language="javascript">

function load_all()
{
    $action
}

</script>
END

    }
}
print process('end_html.tt');
exit;


sub restore_data($)
{
    my $ref = shift;
    my $filename = shift;
    if ($filename && $filename =~ /([\w\.]+)/)
    {
	my $file = ElchemeaConfig->new('/tmp/'.$1);
	foreach my $key ('xmin','xmax','ymin','ymax','title','scale','y2min','y2max')
	{
	    $$ref{$key} = $file->get_config_value('plot',$key);
	}
	foreach my $key ('labels','ltype','style','key','color','mode','admode','user_def')
	{
	    $$ref{$key} = ucfirst($file->get_config_value('plot',$key));
	}
	my $lines = $file->get_config_value('Comments','lines');
	my @ln = ();
	for (my $x = 0; $x < $lines; $x++)
	{
	    push @ln,$file->get_config_value('Comments',$x);
	}
	$$ref{'comments'} = join("\n",@ln);
	my $files = $file->get_config_value('plot','files');
	my @filelist = ();
	my %labels = ();
	for (my $x = 1; $x < $files+1; $x++)
	{
	    my $sec = 'File_'.$x;
	    my $name = $$.'_'.$file->get_config_value($sec,'name').'.data';
	    my $label = $file->get_config_value($sec,'label');
	    my @data = ();
	    my $points = $file->get_config_value($sec,'lines');
	    for (my $y = 0; $y < $points; $y++)
	    {
		push @data,$file->get_config_value($sec,$y);
	    }
	    my $f = SemaforeFile->new('/tmp/'.$name);
	    $f->writeline(@data);
	    push @filelist,$name;
	    $labels{$name} = $label;
	}
	$$ref{'filelist'} = \@filelist;
	$$ref{'filelabels'} = \%labels;
	my $fn = $file->filename();
	unlink $fn if -e ($fn);

	print <<END;
	
<script language="javascript">

function load_all()
{
    setTimeout("set_filelist()",100);
}

</script>
END
    }
    ### Possible cleanum of /tmp ##
}

sub main_form
{
    my %data = (
		'xmin' => '',
		'xmax' => '',
		'ymin' => '',
		'ymax' => '',
		'y2min' => '',
		'y2max' => '',
		'labels' => 'Top frequencies only',
		'ltype' => 'Normal',
		'user_def' => '10,500',
		'slabels' => '0',
		'style' => 'lines',
		'key' => 'Key top right',
		'color' => 'Color',
		'mode' => 'All',
		'comments' => '',
		'title' => '',
		'src' => "/celltest/logfilenew.png",
		'filelist' => [],
		'filelabels' => {},
		);
    &restore_data(\%data,@_) if (@_);
    end_top_bar();
    print p();
    print '<table width=100% class="table"><tr>';
    print '<td width=5%></td>';
    print '<td width=40%></th>';
    print '<td width=50%></td>';
    print '<td width=5%></td></tr>';
    print start_form(-name=>'control');
    print_hidden();
    print '<tr><td></td><td>';
    ### File list and controls here
    print '<table width=100% class="table" cellspacing=10>';
    print '<tr><td width=50% rowspan=13 valign=top>';

    print '<table width=100% class="table">';
    print '<tr><td colspan=2 width=100% valign=top>';
    print h3('File list');
    my @users = ('');
    my %userlabel = ();
    my $system = '';
    my $dir = '/home/http/html/';
    if (-d $dir)
    {
	$system = 'RFCcontrol';
	opendir (MYDIR,$dir) or die "Could not open directory $dir $!\n";
	@users = grep {/rig\d+/} readdir MYDIR;
	closedir MYDIR;
	%userlabel = ('' => 'Rig name:');
    }
    unshift @users,'' unless (param('rig'));
    if (param('session') && $system eq 'RFCcontrol' && !@_)
    {
	print scrolling_list(-name=>'filelist',-values=>[],-size=>27,-multiple=>'true',-class=>'textfield',-onchange=>'set_filelist()',-onDblClick=>'change_legend(this.selectedIndex)',-onkeydown=>'change_order(event)');
    }
    else
    {
	print scrolling_list(-name=>'filelist',-values=>[@{$data{'filelist'}}],-labels=>$data{'filelabels'},-size=>30,-multiple=>'true',-class=>'textfield',-onchange=>'set_filelist()',-onDblClick=>'change_legend(this.selectedIndex)',-default=>[@{$data{'filelist'}}],-onkeydown=>'change_order(event)',-titles=>$data{'filelabels'});
    }
    print '</td></tr><td width=50%>';
    print popup_menu(-name=>'user',-onchange=>'set_user(this.value,"'.$system.'")',-values=>[@users],-class=>'textfield',-default=>'rig'.param('rig'),-labels=>\%userlabel,-id=>'user');
    print '</td><td width=50%>';
    if (param('session'))
    {
	my $id = get_CGI_value_clean('id');
        my @sessions = ();
	my $user = get_CGI_value_clean('rig');
        my $dir = '/home/http/html/rig'.$user.'/';
        if (-d $dir)
        {
           opendir (MYDIR,$dir) or die "Could not open directory $dir $!\n";
           @sessions = grep {/^\d+test\d+$/i} readdir MYDIR;
            closedir MYDIR;
            my %ses = ();
            foreach (@sessions)
            {
                /(\d+)$/;
                $ses{$1} = $_;
            }
            @sessions = ();
            foreach my $key (sort {$a <=> $b} keys %ses)
            {
                push @sessions,$ses{$key};
            }
        }
	my $value = param('session');
	my %labels = ();
	foreach (@sessions)
	{
	    /test(\d+)/;
	    $labels{$1} = $_;
	}
	print popup_menu(-name=>'session',-values=>[sort {$a <=> $b } keys %labels],-default=>$value,-force=>1,-labels=>\%labels,-class=>'textfield',-onchange=>"select_session(this.value,'$system')",-id=>'test');
    }
    else
    {
	print popup_menu(-name=>'session',-values=>[''],-default=>'',-class=>'textfield',-onchange=>"select_session(this.value,'$system')",-id=>'test');
    }
    print '</td></tr><tr><tr><td colspan=2>';
    my $cred = '?name='.$u.'&pass='.$p;
    print button(-name=>'test2',-value=>"Load file from cluster",-class=>'s3',-style=>'height:40px;',-onclick=>"CPLE_open('load_cluster.cgi$cred',400,300,30,30)");
    print '</td></tr></table>';
    print '</td><td colspan=2 valign=top>';
    print h3('Plot control');
    print '</td></tr>';
    print '<tr></td><td width=20%>';
    print popup_menu(-name=>'style',-values=>['Lines','Points','Linespoints'],-default=>$data{'style'},-force=>1,-class=>'textfield',-onchange=>'set_filelist()');
    print '</td><td width=20%>';
    print popup_menu(-id=>'mode',-name=>'mode',-values=>['U vs I','P vs I','ASR vs I','Rsec vs I','All'],-default=>$data{'mode'},-force=>1,-class=>'textfield',-onchange=>'set_mode(this.value)');
    print '</td></tr>';
    print '<tr><td>';
    print popup_menu(-name=>'color',-values=>['Color','Monochrome'],-default=>$data{'color'},-force=>1,-class=>'textfield',-onchange=>'set_filelist()');
    print '</td><td>';
    print popup_menu(-name=>'key',-values=>['Key top right','Key top left','Key bottom right','Key bottom left','No key'],-default=>$data{'key'},-force=>1,-class=>'textfield',-onchange=>'set_mode(this.value)');
    print '</td></tr>';

    print '<tr><td> Title </td><td>';
    print textfield(-name=>'title',-onchange=>'set_title()',-class=>'textfield',-value=>$data{'title'},-force=>1);
    print '</td></tr>';

    print '<tr><td colspan=2><h3 id="range"> Plot range </h3></td></tr>';
    print '<tr><td> X min:';
    print textfield(-name=>'xmin',-onchange=>'set_xmin()',-class=>'textfield',-value=>$data{'xmin'},-force=>1);
    print '</td><td> X max:';
    print textfield(-name=>'xmax',-onchange=>'set_xmax()',-class=>'textfield',-value=>$data{'xmax'},-force=>1);
    print '</td></tr>';
    print '<tr><td> Y min:';
    print textfield(-name=>'ymin',-onchange=>'set_ymin()',-class=>'textfield',-value=>$data{'ymin'},-force=>1);
    print '</td><td> Y max:';
    print textfield(-name=>'ymax',-onchange=>'set_ymax()',-class=>'textfield',-value=>$data{'ymax'},-force=>1);
    print '</td></tr>';
    print '<tr id="y2"><td> Y2 min:';
    print textfield(-name=>'y2min',-onchange=>'set_y2min()',-class=>'textfield',-value=>$data{'y2min'},-force=>1);
    print '</td><td> Y2 max:';
    print textfield(-name=>'y2max',-onchange=>'set_y2max()',-class=>'textfield',-value=>$data{'y2max'},-force=>1);
    print '</td></tr>';
    print '<tr><td colspan=2> Additional Gnuplot commands';
    print textarea(-name=>'comments',-value=>$data{'comments'},-force=>1,-class=>'textfield',-rows=>5,-onchange=>'set_filelist()');
    print '</td></tr>';
    print '</table>';
    print end_form();
    print '</td><td>';
    print '<img name="plot" src="'.$data{'src'}.'" id="plot">';
    print '</td></tr></table>';
    print start_form(-name=>'load');
    &action('Load');
    print_hidden();
    print hidden(-name=>'filename',-value=>'',-force=>1);
    print hidden(-name=>'session',-value=>param('session'),-force=>1);
    print hidden(-name=>'rig',-value=>param('rig'),-force=>1);
    print hidden(-name=>'id',-value=>param('id'),-force=>1);
    print hidden(-name=>'loadrig');
    print hidden(-name=>'loadtest');
    print hidden(-name=>'loadiv');
    print hidden(-name=>'filedata');
    print end_form();

    
    &print_js_manipulate($system);
}


sub print_js_manipulate($)
{
    my $id = $$;
    my $system = shift;
    my ($name,$pass) = &get_id();
    print <<END;

<script language="javascript">

var imgok = false;
var first = true;
var cred = '&name=$name&pass=$pass';


function set_list(res)
{
    var arr =  res.split("\\n");
    if (arr[0] != "OK")
    {
        alert(res);
        return false;
    }
    var rig = document.getElementById('user').value;
    var reg = /(\\d+)/;
    var a = reg.exec(rig);
    var rignr = a[0];
    var testnr = document.control.session.value;
    var element = document.control.filelist;
    element.length = 0;
    for (x = 1; x < arr.length; x++)
    {
	if (arr[x] != '')
	{
	    var newOption = document.createElement('option');
	    newOption.value='$id'+'_'+arr[x];
	    newOption.text=rignr+'test'+testnr+'-'+arr[x];
            newOption.title=rignr+'test'+testnr+'-'+arr[x];
	    element.options.add(newOption);	
	}
    }
    if (first && element.length==1)
    {
	first = false;
	element.selectedIndex = 0;
	set_mode(document.getElementById('mode').value);
    }
}

function load_submit()
{
    var rig = document.load.loadrig.value;
    var test = document.load.loadtest.value;
    var iv = document.load.loadiv.value;
    var reg = /^(\\d+)/;
    var arr = reg.exec(iv);
    var id = rig+'test'+test+'-'+arr[0];
    var label = rig+'test'+test+'-'+iv;
    var element = document.control.filelist;
    var newOption = document.createElement('option');
    newOption.value=id;
    newOption.text=label;
    element.options.add(newOption);	
    element[element.length-1].selected = true;
    set_filelist();
}



function select_session(session,sys)
{
    var q = "&action=rig_iv_list&furnace="+document.load.rig.value+"&runnr="+session+"&id=$id"+cred;
    run_ajax('ajax_interface.cgi',q,set_list);
}

function set_session(res)
{
    var arr =  res.split("\\n");
    if (arr[0] != "OK")
    {
        alert(res);
        return false;
    }
    document.control.filelist.length = 0;
    var element = document.control.session;
    element.length = 0;
    var rig = document.getElementById('user').value;
    var reg = /(\\d+)/;
    var a = reg.exec(rig);
    var newOption = document.createElement('option');
    newOption.value = 0;
    newOption.text = 'Select test:';
    element.options.add(newOption);	
    for (x = 1; x < arr.length; x++)
    {
	var newOption = document.createElement('option');
	newOption.value = arr[x];
	newOption.text = a[0]+'test'+arr[x];
	element.options.add(newOption);	
    }
}

function set_user(user,sys)
{
    run_ajax('ajax_interface.cgi',"&action=run_list&furnace="+user+cred,set_session);
}

function save_plot()
{
    var q = get_querystr();
    RFC_open('ajax_multi.cgi?action=save&ajax=1'+q,600,500,30,30);
}

function load_plot()
{
    RFC_open('load_multi.cgi',600,500,30,30);
}

function change_legend(id)
{
    var name = document.control.filelist[id].value;
    var newtext = prompt("Input new label for file '"+name+"'",document.control.filelist[id].text);
    if (newtext == null)
    {
	return false;
    }
    if (newtext =="" || newtext == " ")
    {
	document.control.filelist[id].text = document.control.filelist[id].value;
    }
    else
    {
	document.control.filelist[id].text = newtext;
    }
    set_filelist();
}

function set_title(r)
{
    set_filelist();
}


function set_xmin()
{
    set_filelist();
}

function set_xmax()
{
    set_filelist();
}

function set_ymin()
{
    set_filelist();
}

function set_ymax()
{
    set_filelist();
}

function set_y2min()
{
    set_filelist();
}

function set_y2max()
{
    set_filelist();
}

function set_mode(m)
{
    var reg = /All/;
    e = document.getElementById('y2');
    if (reg.test(m))
    {
	e.style.display = '';
    }
    else
    {
	e.style.display = 'none';
    }
    set_filelist();
}

function set_image(res)
{
    var arr =  res.split("\\n");
    if (arr[0] != "OK")
    {
        alert(res);
        return false;
    }
    var img = document.getElementById("plot");
    img.src = '/multiplot/' + arr[1] + "?" + Math.random();
    imgok = true;
}

function save_ps()
{
    if (imgok == false)
    {
	return false;
    }
    var img = document.getElementById("plot");
    var src = img.src;
    src = src.replace(/\\.png/,".ps");
    RFC_open(src,600,500,30,30);
}

function get_querystr()
{
    var reg = /[\\#\\:]/;
    var form = document.control;
    var list = form.filelist;
    var selectarr = [];
    for (var i = 0; i < list.length; i++)
    {
	if (list.options[i].selected == true)
	{
            if (reg.test(list.options[i].value+list.options[i].text))
            {
		alert("':' or '#' is not allowed in filenames or file text!");
		return false;
            }
	    selectarr.push(list.options[i].value+':'+list.options[i].text);
	}
    }
    var s = form.style;
    var m = form.mode;
    var xmin = form.xmin.value;
    var xmax = form.xmax.value;
    var ymin = form.ymin.value;
    var ymax = form.ymax.value;
    var y2min = form.y2min.value;
    var y2max = form.y2max.value;
    var color = form.color.value;
    var key = form.key.value;
    var comm = form.comments.value;
    var session = form.session.value;
    var title = form.title.value;
    var user = form.user.value;
    var q = "&filenames="+selectarr.join(',')+"&session=$id&style="+s.value+"&mode="+m.value+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&y2min="+y2min+"&y2max="+y2max+"&color="+color+"&key="+key+"&comm="+comm+"&usersession="+session+"&user="+user+"&system=$system"+"&title="+title;
    q = q.replace(/\\n/g,"%0A");
    q = q.replace(/\\+/g,"%2B");
    return q;
}

function set_filelist()
{
    var q = get_querystr();
    if (q === false)
    {
	return false;
    }
    run_ajax('ajax_multi.cgi','&action=plot'+q+cred,set_image);
}

function load_file()
{
    var q = "&action=save_file&filename="+document.sofc.filename.value+"&data="+document.sofc.data.value+"&session=$id";
    q = q.replace(/\\n/g,"%0A");
    q = q.replace(/\\+/g,"%2B");
    q = q.replace(/\\t/g,',');
    run_ajax('ajax_multi.cgi',q+cred,add_file);
}

function add_file(res)
{
    var arr =  res.split("\\n");
    if (arr[0] != "OK")
    {
        alert(res);
        return false;
    }
    var element = document.control.filelist;
    var newOption = document.createElement('option');
    newOption.value=arr[1];
    newOption.text=arr[2];
    element.options.add(newOption);
    element.options[element.length-1].selected = true;
    set_filelist();
}

function sofc_submit()
{
    load_file();
}


function change_order(event)
{
    var element = document.control.filelist;
    if (element.length < 2)
    {
	return false;
    }
    var x = element.selectedIndex;
    var keyCode = ('which' in event) ? event.which : event.keyCode;
    if (keyCode == 85)
    {
	/* Up */
	if (x == 0)
	    return false;
	var newOption = document.createElement('option');
	newOption.value = element.options[x-1].value;
	newOption.text = element.options[x-1].text;
	element.options[x-1].text = element.options[x].text;
	element.options[x-1].value = element.options[x].value;
	element.options[x].value = newOption.value;
	element.options[x].text = newOption.text;
	element.options[x-1].selected = true;
	element.options[x].selected = false;
    }
    if (keyCode == 68)
    {
	/* Down */
	if (x == element.length-1)
	    return false;
	var newOption = document.createElement('option');
	newOption.value = element.options[x+1].value;
	newOption.text = element.options[x+1].text;
	element.options[x+1].text = element.options[x].text;
	element.options[x+1].value = element.options[x].value;
	element.options[x].value = newOption.value;
	element.options[x].text = newOption.text;
	element.options[x+1].selected = true;
	element.options[x].selected = false;
    }
}

var q = "&action=rig_iv_list&furnace="+document.load.rig.value+"&runnr="+document.load.session.value+"&filenr="+document.load.id.value+"&id=$id";
run_ajax('ajax_interface.cgi',q+cred,set_list);


</script>


END

}
