package YHHN;

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

use Data::Dumper;

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

has log_file => ( is => 'ro', required => 1 );
has request_id_map => ( is => 'rw', isa => 'HashRef[Str]', default => sub { {} });
has $_ => ( is => 'rw', isa => 'HashRef[Str]', default => sub { {} })
    foreach qw(nhs_numbers_map practice_ids patient_id_nhs_number_map);

__PACKAGE__->meta->make_immutable;

$|++;

# rebuilds:

sub convert {
    my $self = shift;
    
    $self->do_demographics();
}

sub do_demographics {
	my $self = shift;
	
    my $dbix3 = $self->db->{dbix3};
    my $dbix4 = $self->db->{dbix4};
	
	my $table = 'hmrn.patient_details';
	
	$self->clear_table($table);
    
	# get organisation_codes like '[^BCY]____' from referral_sources:
	my $practices_map = $self->referral_source_practices;

    # get distinct yhhn.gp_id's (ie org_code):
	my $yhhn_practices = $dbix3->query(
        q!select distinct(gp_id) from yhhn.demographics
        where gp_id is not null and gp_id <> 'B00000'!
    )->flat;

	# ensure all practices in yhhn.demographics exist in referral_sources:
	$self->add_new_practices_to_referral_sources($yhhn_practices); # return;

	# get referral_source.id for unknown practice:
	$dbix4->query(q!select id from referral_sources where organisation_code = 'V81999'!)
		->into( my $unknown_practice_id); # warn $unknown_practice_id; 

    # get demographics table data:
	my $query = $dbix3->query( q!select * from yhhn.demographics! );
    DATA:
	while ( my $vals = $query->hash ) {
		# my $hilis3_patient_id = $vals->{d_pid};
		
        my $nhs_number = $dbix3->query(
			'select NHSNo from PID where P_ID = ?', $vals->{d_pid}
		)->list || next DATA; # warn $nhs_number;
        
        # skip if already seen nhs number:
        next DATA if $self->nhs_numbers_map->{$nhs_number}++;
        
		my $hilis4_patient_id = $dbix4->query(
			'select id from patients where nhs_number = ?', $nhs_number
		)->list;
		
		# add to patient_id => nhs_number_map:
		$self->patient_id_nhs_number_map->{$hilis4_patient_id} = $nhs_number;
		
        my $gp_code = $vals->{gp_id} || '';
        $gp_code =~ s/\s//g; # trim blank spaces!!
        
        my $status = $vals->{dod} ? 'dead' : 'alive';
        
        my %data = (
            patient_id => $hilis4_patient_id,
            status     => $status,
			timestamp  => $vals->{timestamp},
        );
        # add address & post_code if exists:
        map {
            $data{$_} = $vals->{$_}
        } grep $vals->{$_}, qw(address post_code dod);
		
        # add practice_id if exists (document if not):
        if ( my $practice_id = $practices_map->{$gp_code} ) {
            $data{practice_id} = $practice_id;
        }
        else {
			$data{practice_id} = $unknown_practice_id;
            $self->practice_ids->{$gp_code}++; # next DATA unless $practice_id;
        }
        
        $dbix4->insert('patient_demographics', \%data);
    }
    warn Dumper $self->practice_ids;
    while ( my ($nhs_number, $freq) = each %{ $self->nhs_numbers_map } ) {
        next unless $freq > 1;
        warn $nhs_number, "\n";
    }
	# warn Dumper $self->patient_id_nhs_number_map;
}

1;