package MpmasQLTableDefinition;
use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use SimpleObject;
use IndexedTable;
use MpmasQLFunctionLanguage;
use Carp;
our @ISA = qw(SimpleObject);

##sub create{}: inherits create from SimpleObject

##sub new : alternative constructor with prototype
sub new {
      my ($class,  $type, $numkeys, $string, $id)  = @_;
      
      my $self ={};   
      $self->{id} = $id;
      $self->{type} = $type;     
      $self->{keys} = $numkeys;       
      $self->{content} = $string;       
      bless $self, $class;
      return $self;
}

sub id {
    return $_[0]->{id};
}
sub type {
    return $_[0]->{type};
}
sub keys {
    return $_[0]->{keys};
}
sub set_keys {
    $_[0]->{keys} = $_[1];
}
sub content {
    return $_[0]->{content};
}
sub set_content {
     $_[0]->{content} = $_[1];
}
sub concat_to_content {
    if (exists $_[0]->{content}) {
	  $_[0]->{content} .= $_[1];
    }
    else {
	  $_[0]->{content} = $_[1];
    }
}
sub transform {
	my ($self,$dbh, $numkeys) = @_;
	my $temp;
	
	eval { 	$temp = MpmasQLFunctionLanguage->translate_and_interprete($self->content,{}); };
	croak "Error: when interpreting string for table ".$self->id.":\n $@"  if $@;

	$self->set_keys($numkeys) if (not defined $self->keys and defined $numkeys);
	croak "Error: number of keys not set for table ".$self->id."\n" unless (defined $self->keys );
	
	my $newtable;
	if ($self->type eq "sql") {
	      my $string = $temp->[0];
	      croak "Error: To use sql tables you need to specify a database connection (Table: ".$self->id.")\n" unless (defined $dbh);
	      eval{	$newtable = IndexedTable->create_from_SQL($dbh, $string, $self->keys, $self->id) };
	      croak "Error: when running query for table ".$self->id.":\n$@"  if $@;
	}
	elsif ($self->type eq "ascii") {
	      my $string = $temp->[0];
	      eval{	$newtable = IndexedTable->create_from_ascii( $string, $self->keys, $self->id) };
	      croak "Error: when opening file for table ".$self->id.":\n$@"  if $@;
	}
	elsif ($self->type eq "list") {
	      my %hash = map { $_ => 1 } @$temp;
	      eval{	$newtable = IndexedTable->create_from_hash(\%hash, 1, $self->id) };
	      croak "Error: when creating list table ".$self->id.":\n$@"  if $@;
	}
	elsif ($self->type eq "here") {
	      my $sep = '\s*\|\s*';
	      my $end = '\s*§\s*';
		  my $string = $temp->[0];
		   
	      eval{	$newtable = IndexedTable->create_from_string($string,$sep, $end,  $self->keys, $self->id, 1) };
	      croak "Error: when creating here table ".$self->id.":\n$@"  if $@;
	      # print "here for ". $self->id."\n";
	      #$newtable->printme();
	}
	elsif ($self->type eq "link") {      
		  my $string = $temp->[0];
	      $newtable = MpmasQLFunctionLanguage->table_link($string);
	}
	return $newtable;
}
