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

my $ref = &RFC::RFCCGI::get_user_data_ref();
my $uid = $$ref{'uid'};

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

sub main_page()
{
    my %data = ();
    my $r = &get_CGI_value_clean('rig');
    my $type = get_CGI_value_clean('type');
    if ($r)
    {
	my $rig = RFC::Rig->new($r);
	my @devicelist = $rig->list_types();
	$data{'classes'} = [@devicelist];
	my %h = ();
	foreach (@devicelist)
	{
	    $h{$_} = ucfirst($rig->get_uiname($_));
	}
	$data{'classnames'} = \%h;
	my @list = sort {lc($a) cmp lc($b)} $rig->avaliable_devices_nofilter($type);
	$data{'devices'} = [@list];
	print process('device_config.tt',&get_template_data_ref(\%data));
	my $dname = &get_CGI_value_clean('device');
	if ($type && $dname)
	{
	    eval {
		my $dev = $rig->init_device($type,$dname);
		if ($dev)
		{
		    my $checked = 0;
		    foreach ($rig->list_names($type))
		    {
			$checked = 1 if ($_ eq $dname);
		    }
		    $data{'enabled'} = $checked;
		    $data{'class'} = $type;
		    $data{'name'} = $dev->name();
		    $data{'mode'} = $dev->mode();
		    $data{'UIname'} = $dev->UIname();
		    $data{'type'} = $dev->type();
		    $data{'type'} = 'ICP' if ($data{'type'} eq 'SimpleICP');
		    $data{'type'} = 'Keithley580' if ($data{'type'} eq 'KeithleyMicroohmmeter');
		    $data{'type'} = 'ICP7017/18' if ($data{'type'} eq 'SimpleICP7017/18');
		    $data{'type'} = 'ICP7017ZW' if ($data{'type'} eq 'SimpleICP7017ZW');
		    $data{'type'} = 'ICP7019' if ($data{'type'} eq 'SimpleICP7019/87019');
		    $data{'type'} = 'Modbus' if ($data{'type'} eq 'SimpleModbus');
		    $data{'section'} = $dev->sectionname();
		    my @tags = ();
		    my @subtypes = RFC::Device::list_device_types($type);
		    my $id = 'type';
		    $id = 'mode' if ($type eq 'templog');
		    my %h = (
			'id' => $id,
			'change_reload' => 1,
			'description' => 'Device subtype',
			'readonly' => 'Read-write',
			'readonly_value' => '',
			'values' => [@subtypes],
			'hide' => 0,
			'value' => $data{'type'},
			);
		    push @tags,\%h unless (($type eq 'templog' && ref($dev) =~ /Euro/i) || $type eq 'multiplex' || $type eq 'logic');
		    foreach my $tag ($dev->setup_tags())
		    {
			next if ($type eq 'templog' && $tag eq 'mode');
			my $value = $dev->get_conf($tag);
			$value = $dev->get_default($tag) unless ($value);
			my @values = $dev->get_tag_values($tag);
			my %h = (
			    'id' => $tag,
			    'change_reload' => $dev->change_reload($tag),
			    'description' => $dev->tag_description($tag),
			    'readonly' => $dev->tag_type($tag),
			    'readonly_value' => $dev->readonly_value($tag),
			    'values' => [@values],
			    'hide' => $dev->hide_tag($tag),
			    'value' => $value,
			    );
			push @tags,\%h;
		    }
		    $data{'tags'} = [@tags];
		    $data{'template'} = $dev->setup_template();
		    my @fn = ();
		    foreach my $key ($dev->ui_fn_names())
		    {
			my %h = (
			    'name' => $key,
			    'description' => $dev->ui_fn_description($key),
			    'args' => $dev->ui_fn_args($key),
			    );
			push @fn,\%h;
		    }
		    $data{'ui_fn_names'} = [@fn];
		    if ($type eq 'multiplex')
		    {
			my @gasses = ();
			my $controler = 0;
			foreach my $c ($rig->list_devices('MFC'))
			{
			    my $dev = $rig->get_device('MFC',$c);
			    next unless ($dev->multiplexer && $dev->multiplexer->name eq $dname);
			    @gasses = $dev->gasses();
			    $controler = $dev->name;
			}
			$data{'gasses'} = [@gasses];
			$data{'MFC'} = $controler;
			my @gaslist = ();
			foreach my $gas (@gasses)
			{
			    if ($dev->type eq 'VICI')
			    {
				my $port = $dev->get_conf($gas.'_port');
				my $maxch = $dev->get_channels();
				my @list = (1..$maxch);
				my %h = (
				    'type' => 'VICI',
				    'gas' => $gas,
				    'name' => $gas.'_port',
				    'value' => $dev->{'_gas_link'}{$gas},
				    'values' => [@list],
				    'device' => 0,
				    );
				push @gaslist,\%h;
			    }
			    elsif ($dev->type eq 'Slave multiplexer')
			    {
				my @list = ();
				@list = @{$dev->{'_master_gasses'}} if ($dev->{'_master_gasses'});
				my %h = (
				    'type' => 'Slave',
				    'gas' => $gas,
				    'name' => 'gas_link_'.$gas,
				    'value' => $dev->{'_gas_link'}{$gas},
				    'values' => ['',@list],
				    'device' => 1,
				    );
				push @gaslist,\%h;
			    }
			    else
			    {
				my @devs = ('',$rig->avaliable_devices('relay'));
				my $devname = $rig->get_cv('gas_multiplexer_'.$dev->name,$gas.'_device_name');
				my %h = (
				    'type' => 'Relay',
				    'gas' => $gas,
				    'name' => $gas.'_device_name',
				    'value' => $devname,
				    'values' => [@devs],
				    'device' => 1,
				    );
				push @gaslist,\%h;
			    }			    
			}
			$data{'gaslist'} = [@gaslist];
		    }
		    if ($type eq 'gas')
		    {
			my @controler = ();
			foreach my $mfc ($rig->avaliable_devices('MFC'))
			{
			    my $mfcdev = $rig->get_device('MFC',$mfc);
			    my @glist = ();
			    @glist = $mfcdev->gasses() if ($mfcdev);
			    my $gstr = join(' ',@glist);
			    push @controler,$mfc if ($gstr =~ /\b$dname\b/);
			}
			$data{'controlers'} = [@controler];
			if (@controler == 1 && $dev->mode =~ /auto/i)
			{
			    my $ok = 1;
			    if ($data{'controler'} ne $controler[0])
			    {
				$rig->proglog("Warning MFC setup for gas $dname incorrect (was $data{'controler'}, should be $controler[0]), correcting...",&get_user());
				eval {
				    $rig->begin;
				    $rig->change_config_value('gas_'.$dname,'controler',$controler[0]);
				    $rig->init();
				    $rig->commit();
				};
				if ($@)
				{
				    $rig->rollback();
				    $rig->proglog("Error: Could not correct MFC setup for gas $dname $@",&get_user());
				    print "<th class='Alert'> Error: ".xss($@)." </th>";
				    $ok = 0;
				}
			    }
			    if ($ok)
			    {
				$data{'controler_id'} = $controler[0];
			    }
			    else
			    {
				$data{'controler_id'} = 0;
			    }
			}
		    }
		}
	    };
	    if ($@)
	    {
		print h3({-class=>'Alert'},$@);
	    }
	    print process('device_setup/'.$data{'template'},&get_template_data_ref(\%data));
	}
    }
}
