#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:standard :netscape);
use RFC::Main;
use RFC::Rig;
use RFC::RFCCGI qw(:cgi :html);
use JSON qw(decode_json);
use MIME::Base64;

my $ref = &RFC::RFCCGI::get_user_data_ref();
my $uid = $$ref{'uid'};
my $template_path = $RFC::Header::htmldir.'templates/rigs/';

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

sub set_default()
{
    &save_gui();
    my $rig = RFC::Rig->new(param('rig'));    
    my $name = &get_CGI_value_clean('template_name');
    my $file = lc("$rig").'_'.$name.'.tt';
    $file =~ s/\s/\_/g;
    $rig->change_config_value('userinterface','default_layout',$file);
}

sub save_gui()
{
    my $rig = RFC::Rig->new(param('rig'));    
    my $name = &get_CGI_value_clean('template_name');
    my $file = $template_path.lc("$rig").'_'.$name.'.tt';
    $file =~ s/\s/\_/g;
    my $model = encode_base64(param('model'));
    $model =~ s/[\s\n\t]+//g;
    my $xmax = get_CGI_value_clean('x');
    my $ymax = get_CGI_value_clean('y');
    my $ref = decode_json(param('model'));
    open MYOUT,'>',$file or die "Could not open file for writing $!\n";
    print MYOUT "<!-- Template $name for rig $rig -->\n";
    print MYOUT '[%# json_model = ',$model,' %]',"\n";
    print MYOUT "\n";
    print MYOUT "<div class=rig_model>\n";
    print MYOUT "<table class=model_tab>\n";
    for (my $y = 0; $y < $ymax; $y++)
    {
	print MYOUT "<tr>\n";
	for (my $x = 0; $x < $xmax; $x++)
	{
	    my $id = $x.'_'.$y;
	    if ($$ref{$id})
	    {
		my $template = $$ref{$id}{'template'}.'.tt';
		my $type  = $$ref{$id}{'type'};
		my $mode  = $$ref{$id}{'mode'};
		my $name  = $$ref{$id}{'name'};
		my $label  = $$ref{$id}{'label'};
		my $labelstr = '';
		$labelstr = "label='$label'" if ($label);
		if ($template eq 'Tempcontrol.tt' || $template eq 'PSU.tt' || $template eq 'PID.tt' || ($template eq 'simple.tt' && $type eq 'device' && $mode ne 'pressure' && $mode ne 'DPS'))
		{
		    print MYOUT "<td class='model_cell model_cell_top_margin'>\n";
		}
		else
		{
		    print MYOUT "<td class=model_cell>\n";
		}
		if ($name)
		{
		    print MYOUT "[% INCLUDE devices/$template class='$type' name='$name' mode='$mode' $labelstr %]\n";
		}
		else
		{
		    print MYOUT "[% INCLUDE devices/$template class='$type' $labelstr %]\n";
		}
		print MYOUT "</td>\n";
	    }
	    else
	    {
		print MYOUT "<td class=model_cell>\n";
		print MYOUT "</td>\n";
	    }
	}
	print MYOUT "</tr>\n";
    }
    print MYOUT "</table>\n";
    print MYOUT "</div>\n";
    close MYOUT;
}

sub main_page()
{
    my %data = ();
    my $rig = RFC::Rig->new(param('rig'));    
    if (param('action') && param('action') eq 'load')
    {
	my $name = &get_CGI_value_clean('template_name');
	$data{'template_name'} = $name;
	my $file = $template_path.lc("$rig").'_'.$name.'.tt';
	$file =~ s/\s/\_/g;
	if (-e $file)
	{
	    open MYIN,'<',$file or die "Cant open file $!\n";
	    while (my $line = <MYIN>)
	    {
		next unless ($line =~ /json_model\s*=\s*([\w\+\/\=]+)/);
		my $model = decode_base64($1);
		param(-name=>'model',-value=>$model);
		last;
	    }
	    close MYIN;
	}
    }
    if (param('model'))
    {
	my $maxx = 2;
	my $maxy = 2;
	my $ref = decode_json(param('model'));
	foreach my $key (keys %{$ref})
	{
	    my ($x,$y) = split(/_/,$key);
	    $maxx = $x if ($x > $maxx);
	    $maxy = $y if ($y > $maxy);
	}
	$data{'x'} = $maxx+1;
	$data{'y'} = $maxy+1;
	$data{'model'} = $ref;
    }    
    my @devs = $rig->list_devices('relay');
    my @control = $rig->list_devices_control('relay');
    my @relays = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	);
	push @relays,\%h;
    } 
    @devs = $rig->list_devices('water');
    @control = $rig->list_devices_control('water');
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	);
	push @relays,\%h;
    } 
    $data{'devices'}{'relays'} = [@relays];    
    @devs = $rig->list_devices('gas');
    @control = $rig->list_devices_control('gas');
    my @gasses = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	);
	push @gasses,\%h;
    } 
    $data{'devices'}{'gasses'} = [@gasses];    
    @devs = $rig->list_devices('MFC');
    @control = $rig->list_devices_control('MFC');
    my @mfcs = ();
    my @Pcontrols = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my $dev = $rig->get_device('MFC',$key);
	my @gasses = $dev->gasses();
	## Select pressure controls ##
	if ($dev->controler_mode() eq 'Pressure')
	{
	    my %h = (
		'name' => $dev->selected_gas(),
		'readonly' => $readonly,
		);
	    push @Pcontrols,\%h;
	    next;
	}
	## ONLY include multiplextd MFC's
	next unless (@gasses && @gasses > 1);
	my %h = (
	    'name' => $key,
	    'gasses' => [@gasses],
	    'readonly' => $readonly,
	);
	push @mfcs,\%h;
    }
    $data{'devices'}{'MFCs'} = [@mfcs];    
    $data{'devices'}{'Pcontrols'} = [@Pcontrols];    
    @devs = $rig->list_devices('PSU');
    @control = $rig->list_devices_control('PSU');
    my @PSU = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	    'type' => 'PSU',
	);
	push @PSU,\%h;
    } 
    @devs = $rig->list_devices('analog');
    @control = $rig->list_devices_control('analog');
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	    'type' => 'analog',
	);
	push @PSU,\%h;
    } 
    $data{'devices'}{'PSUs'} = [@PSU];    
    @devs = $rig->list_devices('multiplex');
    @control = $rig->list_devices_control('multiplex');
    my @multi = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my $dev = $rig->get_device('multiplex',$key);
	my @l = $dev->gasses();
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	    'gasses' => [@l]
	);
	push @multi,\%h;
    } 
    $data{'devices'}{'Multiplexs'} = [@multi];    
    @devs = $rig->list_devices('tempcontrol');
    @control = $rig->list_devices_control('tempcontrol');
    my @Tcontrol = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	);
	push @Tcontrol,\%h;
    } 
    $data{'devices'}{'Tcontrols'} = [@Tcontrol];    

    @devs = $rig->list_devices('PID');
    @control = $rig->list_devices_control('PID');
    my @PID = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	);
	push @PID,\%h;
    } 
    $data{'devices'}{'PIDs'} = [@PID];    
    @devs = $rig->list_devices('templog');
    @control = $rig->list_devices_control('templog');
    my @Tlog = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	);
	push @Tlog,\%h;
    } 
    $data{'devices'}{'Tlogs'} = [@Tlog];    
    @devs = $rig->list_devices('water');
    @control = $rig->list_devices_control('water');
    my @water = ();
    foreach my $key (@devs)
    {
	my $readonly = 1;
	foreach (@control)
	{
	    next unless ($key eq $_);
	    $readonly = 0;
	    last;
	}
	my %h = (
	    'name' => $key,
	    'readonly' => $readonly,
	);
	push @water,\%h;
    } 
    $data{'devices'}{'waters'} = [@water];
    @devs = $rig->list_devices('simplechannel');
    my @simple = ();
    foreach my $key (@devs)
    {
	my %h = (
	    'name' => $key,
	);
	push @simple,\%h;
    } 
    $data{'devices'}{'simplechannels'} = [@simple];
    opendir DIR,$template_path;
    my $pattern = lc("$rig");
    $pattern =~s/\s+/_/g;
    my @files = sort {$a cmp $b } grep(/^$pattern/,readdir(DIR));
    closedir(DIR);
    foreach (@files)
    {
	s/^rig\_\d+\_//;
	s/\.tt$//;
    }
    $data{'templates'} = [@files];
    print process('setup_gui.tt',&get_template_data_ref(\%data));
}
