package Role::ReferralSource;

use Moose::Role;
use Data::Dumper;

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

sub add_new_practices_to_referral_sources {
	my ($self, $practices) = @_; # warn Dumper $practices; 
	
    my $dbix3 = $self->db->{dbix3};
    my $dbix4 = $self->db->{dbix4};
    
    my $ref_src_practices = $self->referral_source_practices; # warn Dumper $ref_src_practices;

	PRACTICE:
	for my $practice_code (@$practices) { # warn $practice_code;
		$practice_code =~ s/\s//g; # trim blank spaces (for YHHN practices)
		
		# skip existing practices:
		next if $ref_src_practices->{$practice_code}; # warn $practice_code;

		# get details from cm.gp_practices:
		my $sql = qq!select * from community_monitoring.gp_practices where practice_id = ?!;
		my $practice = $dbix3->query($sql, $practice_code)->hash; # warn Dumper $practice;
		
		unless ($practice) {
			warn "no practice found in community_monitoring.gp_practices for $practice_code";
			next PRACTICE;
		} #	next PRACTICE;

		my $parent_organisation_id = $dbix4->query(q!select id from parent_organisations
			where parent_code = ?!, $practice_code)->array;
		
        if (! $parent_organisation_id) { # add practice to parent_organisations & retrieve new id:
            my @address = split ', ', $practice->{address};

            my $description = join ', ', uc $address[0], $practice->{post_code};

            my %data = (
                parent_code => $practice_code,
                description => $description,
                referral_type_id => 5,
            ); # warn Dumper \%data; next PRACTICE;
            $dbix4->insert('parent_organisations', \%data);
         
			$parent_organisation_id
			    = $dbix4->last_insert_id(undef, undef, 'parent_organisations', 'id')
			    || die "Cannot retrieve parent_organisation_id for $practice_code";
        }

        # warn Dumper ($practice_code, $parent_organisation_id);
        my %data = (
            organisation_code => $practice_code,
            referral_type_id  => 5, # practice
            parent_organisation_id => $parent_organisation_id,
            display_name => join ', ', @{$practice}{qw(address post_code)},
        ); # warn Dumper \%data; next PRACTICE;
        $dbix4->insert('referral_sources', \%data);
		
		# add new org_code entry to $ref_src_practices:
		{
			my $referral_sources_id
				= $dbix4->last_insert_id(undef, undef, 'referral_sources', 'id')
				|| die "Cannot retrieve referral_sources.id for $practice_code";
			$ref_src_practices->{$practice_code} = $referral_sources_id;
		}
	} 
}

sub _build_referral_source_practices {
	my $self = shift;
	
	my $sql = q!select organisation_code, id from referral_sources where
		organisation_code like 'B_____' or
		organisation_code like 'C_____' or
		organisation_code like 'P_____' or
		organisation_code like 'Y_____'!;
	
	return $self->db->{dbix4}->query($sql)->map;
}

1;