#!/usr/bin/perl

use warnings;
use strict;

use XML::LibXML;
use Term::ReadKey;

print "Nombre PROPEL de la BD (Ej. \"sirevih\" NO \"sirevih_trunk\"): ";
my $dbname = ReadLine(0);
chomp($dbname);

my $parser = XML::LibXML->new();
my $dom = $parser->parse_file('config/schema.xml');


my @databases = $dom->getElementsByTagName('database');

$databases[0]->setAttribute('name', $dbname);

my @tables = $dom->getElementsByTagName('table');

foreach my $table (@tables) {

    my $tablename = $table->getAttribute('name');

    my @columns = $table->getChildrenByTagName('column');


    foreach my $column (@columns){

	my $colname = $column->getAttribute('name');
	my $coltype = $column->getAttribute('type');
	my $colsize = $column->getAttribute('size');
	my $colpkey = $column->getAttribute('primaryKey');

	# es un pk
	if(
            ( ($colname eq 'id') or ($colname eq 'ID') ) and 
            ( ($coltype eq 'INTEGER') or ($coltype eq 'NUMERIC') ) and
               $colpkey eq 'true'
           ){

            if(&not_slave($tablename)){
                # setear idMethod en la tabla
                $table->setAttribute('idMethod', 'native');

                # asocia secuencia a la tabla
                my $element = $dom->createElement('id-method-parameter');
                $element->setAttribute('value', $tablename.'_id_seq');
                $table->appendChild($element);

                # setear autoIncrement en la columna
                $column->setAttribute('autoIncrement', 'true');
            }
            else {
                # Futuras expansiones
            }

	}

	# corregir booleano
	if( ($coltype eq 'CHAR') and
	    ($colsize eq '1')){

	    $column->setAttribute('type', 'BOOLEAN');
	    $column->setAttribute('default', 'f');

	}


	# cambiar timestamp a date
	if($coltype eq 'TIMESTAMP'){

	    $column->setAttribute('type', 'DATE');

	}


    }


}

# escribir los cambios
# archivo de salida
open(OUTPUT, ">", "config/schema.xml")
    or die "No se pudo abrir schema.xml para escritura";

print OUTPUT $dom->toString;


close OUTPUT;

exit(0);


sub not_slave {

    my $tbname = shift;

    my $not_slave = 1;

    my @slave_tables = qw(gen_censado_juridico
                          censo_respuesta
                          censo_grupo_familiar
                     );

    foreach (@slave_tables){
        $not_slave = 0 if lc($tbname) eq $_;
    }

    return $not_slave;

}
