#!/usr/bin/perl -w
#< some json tests

use strict;
use warnings;
use JSON;
use Time::Local;
use Date::Calc qw(Week_of_Year);
use Time::gmtime;

my %hash = ();
my %h = ();
my @pilots = qw( AAA BBB CCC );
my @air = qw( ac1 ac2 ac3 );

sub prt($) { print shift; }

sub get_scalar($) {
    my $rh = shift;

    my ($pilot,$cnt,$ra,$air,$cnt2);
    $cnt = 0;
    $cnt2 = 0;
    foreach $pilot (@pilots) {
        $cnt++;
        ${$rh}{$pilot}{'total_time'} = $cnt;
        ${$rh}{$pilot}{'aircrafts'} = [];
        $ra = ${$rh}{$pilot}{'aircrafts'};
        foreach $air (@air) {
            $cnt2++;
            my %h2 = ();
            $h2{'aircraft'} = $air;
            $h2{'time'} = $cnt2;
            #push(@{$ra}, [ $air, $cnt2 ]);
            push(@{$ra}, \%h2);
        }
    }
}

my $rh = \%hash;
get_scalar($rh);
$h{'pilots'} = $rh;
$rh = \%h;

my $json_text = encode_json $rh;

print $json_text."\n";

my $json = JSON::XS->new->pretty(1)->encode($rh);

print $json."\n";

my $str = '2007/07/17 13:21';
my $str2 = '24.06.2012 12:48:28';
my $str3 = '26.05.2012 18:39:08';

my @t   = $str =~ m!(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2})!;
$t[1]--;
my $timestamp = timelocal 0,@t[4,3,2,1,0];
# verify...
print $str."\n";
print scalar localtime $timestamp;
print "\n";

@t   = $str2 =~ m!(\d{2})\.(\d{2})\.(\d{4})\s(\d{2}):(\d{2})!;
$t[1]--;
my $tmp = $t[0];
$t[0] = $t[2];
$t[2] = $tmp;
$timestamp = timelocal 0,@t[4,3,2,1,0];
print $str2."\n";
print scalar localtime $timestamp;
print "\n";

my $tm = gmtime($timestamp);
#my $m = sprintf( "%04d/%02d/%02d", $tm->year() + 1900, $tm->mon() + 1, $tm->mday());
my $year = $tm->year() + 1900;
my $month = $tm->mon() + 1;
my $day = $tm->mday();
my ($week,$ayear) = Week_of_Year($year,$month,$day); 
prt("Is week $week of $ayear\n");

@t   = $str3 =~ m!(\d{2})\.(\d{2})\.(\d{4})\s(\d{2}):(\d{2})!;
$t[1]--;
$tmp = $t[0];
$t[0] = $t[2];
$t[2] = $tmp;
$timestamp = timelocal 0,@t[4,3,2,1,0];
print $str3."\n";
print scalar localtime $timestamp;
print "\n";

$tm = gmtime($timestamp);
#my $m = sprintf( "%04d/%02d/%02d", $tm->year() + 1900, $tm->mon() + 1, $tm->mday());
$year = $tm->year() + 1900;
$month = $tm->mon() + 1;
$day = $tm->mday();
($week,$ayear) = Week_of_Year($year,$month,$day); 
prt("Is week $week of $ayear\n");

exit 0;
