#! /usr/bin/env perl

# Test package that computes default database settings:

use strict;
use warnings;
use utf8;

use lib 'lib';
use RestfulDB::DBSettings qw(get_database_settings);

binmode( STDOUT, "utf8" );

my %cgi1 = (
    engine => "MySQL",
);

my %cgi2 = (
    engine => "SQLite2",
);

my %cgi3 = (
    db => "",
    engine => "MySQL"
);

my %env1 = (
    REQUEST_URI => "/tbl",
);

my %env2 = (
    REQUEST_URI => '/dbase/tbl2?param1=1&param2=22',
);

my %env3 = (
    REQUEST_URI => '/',
);

my %env4 = (
    REQUEST_URI => '',
);

my @cases = (
    { env => \%env1, cgi => \%cgi1, par => { db_dir => "./db" } },
    { env => \%env2, cgi => \%cgi1, par => { db_dir => "./db", level => 2 } },
    { env => \%env2, cgi => \%cgi2, par => { db_dir => "./db", level => 1 } },
    { env => \%env1, cgi => \%cgi2, par => { db_dir => "./db", level => 2 } },
    { env => \%env3, cgi => \%cgi1, par => { db_dir => "./db", level => 1 } },
    { env => \%env3, cgi => \%cgi2, par => { db_dir => "./db", level => 2 } },
    { env => \%env4, cgi => \%cgi2, par => { db_dir => "./db", level => 1 } },
    { env => \%env4, cgi => \%cgi1, par => { db_dir => "./db", level => 2 } },
    { env => \%env2, cgi => \%cgi3, par => { db_dir => "./db", level => 1 } },

    { env => \%env2, cgi => { db => "" }, par => { db_dir => "./db", level => 1 } },
);

my $n = 0;
my $separator = "";
for my $case (@cases) {

    print $separator;
    print "test" . $n++ . ":\n";
    $separator = "\n";

    print "REQUEST_URI = $case->{env}->{REQUEST_URI}\n";

    my $settings;
    eval {
        $settings = &get_database_settings( $case->{cgi},
                                            $case->{env},
                                            $case->{par} );
    };
    if( $@ ) {
        print $@;
    } else {
        local $\ = "\n";
        $case->{settings} = $settings;
        for my $argument_name (qw(cgi env par settings)) {
            my $hash = $case->{$argument_name};
            print "$argument_name:";
            for my $key ((sort keys %{$hash})) {
                printf "\t%-21s ", $key;
                print "= ", defined $hash->{$key} ?
                    ("'" . $hash->{$key} . "'") : 'undef';
            }
        }
    }
};
