package Consent;

use Moose;
    with qw(
        Role::RebuildTables
    );
use namespace::clean -except => 'meta';

has db  => (is => 'ro', isa => 'HashRef', required => 1);
has sql => (is => 'ro', isa => 'HashRef', required => 1);

has consent_map => ( is => 'ro', isa => 'HashRef', lazy_build => 1 );

__PACKAGE__->meta->make_immutable;

use Data::Dumper;

my @tables = qw(
    request_consent
);

$|++;

sub convert {
    my $self = shift; # warn Dumper $self;

    my $dbix3 = $self->db->{dbix3};
    my $dbix4 = $self->db->{dbix4};

    $self->rebuild_tables(\@tables);
    
    my $consents = $self->consent_map;
    
    my $sql = q!select HMDS, year(Date) as 'year', Store, Research, Treatment,
        Monitor from Main,Consent where DBID = Con_ID!;
        
    my $src = $dbix3->query( $sql );
    while ( my $vals = $src->hash ) {
		my $request_id = $dbix4->query( q!select id from requests where request_number
			= ? and year = ?!, $vals->{hmds}, $vals->{year})->list;
        
		foreach my $c( keys %$consents ) {
			next unless $vals->{$c};
			
			my %data = (
				request_id => $request_id,
				consent_id => $consents->{$c},
                status     => $vals->{$c},
			);
			$dbix4->insert('request_consent', \%data);
		}		
    }
}

sub _build_consent_map {
    my $self = shift;
    
    my $dbh4  = $self->db->{dbix4};
    
    my $consents = $dbh4->query( 'select consent_name, id from consent_options')->map;
    
    return $consents;
}

1;
