package LIMS::Model::Roles::DBIxSimple;

use Moose::Role;
use DateTime::Format::MySQL;
# requires 'lims_dbix'; # LIMS::Model::Base method

sub get_cols {
	my ($self, $table) = @_;
	
	my $dbh = $self->lims_dbix;
	
	my $meta = $self->get_meta($table); # warn Dumper $meta;
	
	my @cols = keys %$meta; # warn Dumper \@cols;
	return \@cols;
}

sub get_meta {
	my ($self, $table) = @_;
	
	my $dbh = $self->lims_dbix;
	
	my $t = $dbh->query("show columns from $table")->hashes; # warn Dumper $t;
	
	my %meta = map { $_->{field} => $_ } @$t; # warn Dumper \%meta;	
	return \%meta;
}

sub get_enum_opts {
	my ($self, $table, $col) = @_;

	my $meta = $self->get_meta($table);
	
	my $col_type = $meta->{$col}->{type};
	
	my ($enum) = $col_type =~ /enum\((.*)\)/; # warn $enum;
	my @opts = sort grep { $_ =~ s/\'//g } split ',', $enum; # warn Dumper \@opts;
	return \@opts;
}

sub inflate_mysql_dates_to_datetime {
	my $self = shift;
	my $data = shift; # hashref
	my $cols = shift; # array(ref) of cols to inflate
	
	map {
		$data->{$_} = DateTime::Format::MySQL->parse_date($data->{$_});
	} grep $data->{$_}, @$cols;	
}

sub inflate_mysql_timestamp_to_datetime {
	my $self = shift;
	my $data = shift; # hashref
	my $cols = shift; # array(ref) of cols to inflate
	
	map {
		$data->{$_} = DateTime::Format::MySQL->parse_datetime($data->{$_});
	} grep $data->{$_}, @$cols;	
}

1;