#!/bin/bash

# Test package that computes default database settings

TMP_DIR="${TMPDIR}"

test -z "${LIB_DIR}" && LIB_DIR=lib

SCRIPT_BASE=`basename $0 | sed "s/_[0-9]*\.sh$//; s/-/\//g"`

BASENAME=$(basename $0 .pm)

#BEGIN DEPEND------------------------------------------------------------------

INPUT_SCRIPT="${LIB_DIR}/${SCRIPT_BASE}"

#END DEPEND--------------------------------------------------------------------

set -ue
## set -x

test -z "${TMP_DIR}" && TMP_DIR="/tmp"
TMP_DIR="${TMP_DIR}/tmp-${BASENAME}-$$"
mkdir "${TMP_DIR}"

# To make the trap portable between bash and dash, we need to trap
# "signal" 0 ("EXIT") and rely on it for the cleanup:
## trap "rm -rf '${TMP_DIR}'" 0 1 2 3 15
trap "rm -rf '${TMP_DIR}'" EXIT
trap "exit 1" HUP INT QUIT TERM

TMP_DB_MAIN="${TMP_DIR}/test4fk.db"
TMP_DB_META="${TMP_DIR}/restful.db"

cp db/test4fk.db ${TMP_DB_MAIN}
cp db/restful.db ${TMP_DB_META}

sqlite3 ${TMP_DB_MAIN} <<END
    create view sample_experiment as
        select SolsaID, result
        from sample join experiment on sample.id = sample_id;
END

sqlite3 ${TMP_DB_META} "delete from description"
sqlite3 ${TMP_DB_META} "insert into description (id, dbname, dbtable, dbcolumn, coltype, fk_target, relation) values (1, '${TMP_DB_MAIN}', 'experiment', 'sample_id', 'fk', 5, 'N')"
sqlite3 ${TMP_DB_META} "insert into description (id, dbname, dbtable, dbcolumn, coltype) values (5, '${TMP_DB_MAIN}', 'sample', 'id', 'id')"

export TMP_DB_MAIN

perl <<'END'
#! /usr/bin/env perl

# Test package that computes default database settings:

use strict;
use warnings;
use utf8;
use Data::Dumper;

use lib 'lib';
use Database;
use Database::View;

binmode( STDOUT, "utf8" );

$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

my $db_settings = {
    content_db => {
        DB => $ENV{TMP_DB_MAIN},
        engine => 'SQLite'            
    }
};

my $db = Database->new( $db_settings );
$db->connect();
my $view = Database::View->new( $db, 'sample_experiment' );

delete $view->{db};
print "View description:\n";
print Dumper $view;
$view->{db} = $db;

my $data = $db->get_record_descriptions( 'sample_experiment',
                                         { template => 1 } );
$data->[0]{columns}{SolsaID}{value} = 'AM-TEST-0001';
$data->[0]{columns}{result}{value} = 12.345;
print "Record description:\n";
print Dumper $data;

print "Expanded description:\n";
print Dumper $view->expand_record_descriptions( $data );
END

# Temporary directory will be deleted by the trap.
