#! /usr/bin/env perl

# Test package that computes default database settings:

# Check how database name and engine generator reacts to weird
# database names.

use strict;
use warnings;
use utf8;

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

binmode( STDOUT, "utf8" );

my @cases = (
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => {}, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => ".", table => "." }, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => ".", table => "/" }, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => "/", table => "." }, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => "/", table => "/" }, par => {} },

    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => "x", table => "." }, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => "y", table => "/" }, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => ".", table => "z" }, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => "/", table => "t" }, par => {} },

    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => "", table => "tb" }, par => {} },
    { env => {REQUEST_URI => "/test/dbase/tbl"}, cgi => { db => "Db", table => "" }, par => {} },
);

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

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

    $case->{par}{db_dir} = "/tmp/try";

    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';
            }
        }
    }
};
