#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;

&today ;

#------------------------------------------------------------------------------------------

@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'});

foreach $ARG (@ARGV) {
    ($par,$val) = split(/\=/,$ARG) ;
    $val  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;    
    $param{$par} = $val ;
    }
	
my $table = 'cameras' ;

#------------------------------------------------------------------------------------------

print "Content-type: text/html\n\n";

use DBI;
use CGI::Carp qw(fatalsToBrowser);

&get_db_camera_system ;

print $json ;

exit ;

#------------------------------------------------------------------------------------------

sub get_db_camera_system {

my $is_vpu = 0 ; 

if ($param{camera_system_id}) { 

	my @valarr = split(/\:/,$param{camera_system_id}) ;
	$camera_system_id = $valarr[0] ;
	$camera_nr_prefix = $valarr[1] ;
	
	# &db_min_ro($table,'id,camera_nr',"`camera_system_id`='$camera_system_id'",'','') ;
	&db_min_ro($table,'id,camera_nr',"`camera_system_id`='$camera_system_id'",'`id` DESC',1) ;
	
	foreach my $id (keys %{$db{$table}}) { 
		my ($cam_type,$cam_cnt) = split(/\-/,$db{$table}{$id}{camera_nr});
		$max_cam_cnt{$cam_type} = $cam_cnt unless $max_cam_cnt{$cam_type} > $cam_cnt ;
	}
	&db_min_ro('camera_systems','*',"name like '%S1%'",'','') ;
	foreach (keys %{$db{camera_systems}}) {		
		$is_vpu = 1 if $_ eq $camera_system_id ;
	}
}
$max_cam_cnt{$camera_nr_prefix}++ ;

my $camera_nr = $camera_nr_prefix . '-' . sprintf("%04s", $max_cam_cnt{$camera_nr_prefix}) ; # e.g. S1-0001

$json = qq~[{"camera_nr":"$camera_nr","vpu":"$is_vpu"}]~ ;
   
} #------------------------------------------------------------------------------------------

use db ;
use today ;
use common ;

1;