#!/usr/bin/perl

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use JSON::XS;
use FileHandle;
use XML::XPath;
use XML::Hash::XS;
use JSON::Validator;
use JSON::Validator::Schema::Draft7;
use Text::CSV::Easy(qw/csv_build csv_parse/);

use lib '/var/app/orchard/collab/jgetter/perllib';
use Orchard::Session;

my $jv = JSON::Validator->new();

my $schema = JSON::Validator::Schema::Draft7->new('file://contract_schema.json');

my $file = shift @ARGV or die "requires JSON file";
my $fh   = FileHandle->new( $file, 'r' );
while (<$fh>) {
    chomp;

    my ( $id, $json ) = split ',', $_;
    logMessage( 'info', "Parsing JSON for account: $id" );

    my $href = JSON::XS::decode_json($json);
    my $xml  = hash2xml($href);
    my $xp   = XML::XPath->new( 'xml' => $xml );

    my $errs = [ $jv->validate( $href, $schema ) ];
    if ( defined $errs and scalar @{$errs} ) {
        foreach my $err ( @{$errs} ) {
            my $path = $err->path;
            if ( $path =~ m/[0-9]/ ) {
                $path =~ s!([0-9])!$1+1!eg;
                $path =~ s!/([0-9])![$1]!g;
            }
            my $text = "'" . $xp->getNodeText( '/root' . $path ) . "'";
            logMessage( 'error1', $path . " - [ $text ] - " . $err->message );
        }
    } else {
        logMessage( 'info1', 'valid JSON' );
    }
}
