package LIMS::Model::Ajax;

use strict;
use Data::Dumper;

use base 'LIMS::Model::Base';

#-------------------------------------------------------------------------------
sub check_exists {
    my $self = shift;
    my $args = shift; # $self->debug($args);

	my ($field_name, $class_method, $query);
	
	# func can be scalar or arrayref:
	if (ref $args->{func} eq 'ARRAY') { # arrayref of [field_name, class/method]
		($field_name, $class_method) = @{ $args->{func} };
		# need to create $query with key = $field_name, value = $vars value:
		my ($key, $param) = %{ $args->{vars} };
		$query = { $field_name => $param };
	}
	else { # $func is a scalar value for class/method eg 'diagnosis'
		$class_method = $args->{func};
		$query        = $args->{vars};
	}

    # create classname from class_method, split on hyphen, rejoin with
	# ucfirst (eg lab_test -> LabTest):
    my $class_name = join '', map { ucfirst $_ } split '_', $class_method; 

    # create full package name  # eg LIMS::DB::LabTest::Manager
    my $package  = join '::', 'LIMS', 'DB', $class_name, 'Manager';

    # create method name for Manager class # eg lab_test -> get_lab_tests_count:
    my $function = sprintf 'get_%s_count', "${class_method}s";

    # do query:
#$self->set_rose_debug(1);
    my $count = $package->$function(query => [ %$query ]);
#$self->set_rose_debug(0);

    return $count;
}

#-------------------------------------------------------------------------------
sub get_email_addresses {
    my $self  = shift;
    my $param = shift; # $self->debug($param);

    my %args = (
		query => [ address => { like => $param->{address} . '%' } ],
	);
	
	my $addresses = LIMS::DB::EmailAddress::Manager->get_email_addresses(%args);
	return $addresses;
}

#-------------------------------------------------------------------------------
sub get_clinicians_for_source {
    my $self  = shift;
    my $param = shift;

    my %args = (
		query => [
			'referral_sources.id' => $param->{source_id},
			'referrers.name' => { like => $param->{referrer_name} . '%'},
            'is_active' => 'yes', # ok, defaults to t1 if table not specified
		],
		with_objects => [
            qw(
                parent_organisation.referral_source
                hospital_department
                referrer
            ),
        ],
		sort_by => 'referrer.name',
	);
#$self->set_rose_debug(1);
	my $referrer_department
        = LIMS::DB::ReferrerDepartment::Manager->get_referrer_department(%args);
#$self->set_rose_debug(0);

    return $referrer_department;
}

#-------------------------------------------------------------------------------
sub get_referral_sources {
	my $self = shift;
	my $args = shift;
	
    my %args_for_query = (
        query   => [ display_name => { like => '%' . $args->{location} . '%' } ],
		require_objects => 'referral_type',
        sort_by => [ 'referral_type.description', 'display_name' ], # hospitals 1st
        limit   => 10,
    );

	# only want hospitals for new clinician entry:
	push @{ $args_for_query{query} }, ( description => 'hospital' )
		if $args->{hospitals_only};
	
    # only want active locations for register & edit:
	push @{ $args_for_query{query} }, ( is_active => 'yes' )
		if $args->{active_only};

    my $sources
		= LIMS::DB::ReferralSource::Manager->get_referral_sources(%args_for_query);	
	
	return $sources;	
}

#-------------------------------------------------------------------------------
sub get_parent_organisations {
	my $self = shift;
	my $args = shift;

    my %args_for_search = (
        query   => [
			description => { like => '%' . $args->{organisation} . '%' },
			'referral_types.description' => { ne => 'practice' },
		],
		require_objects => 'referral_type',
        sort_by => 'description',
        limit   => 10,
    );

    my $organisations = LIMS::DB::ParentOrganisation::Manager
		->get_parent_organisations(%args_for_search);
		
	return $organisations;
}

# ------------------------------------------------------------------------------
sub get_practice_by_practitioner {
    my ($self, $gp_name) = @_; # warn Dumper $gp_name;
    
    my @args = (
        query => [
            'referrer.name' => { like => $gp_name .'%' },
            'parent_organisation.referral_source.referral_type.description'
                => 'practice',
        ],
        require_objects => [
            'referrer',
            'parent_organisation.referral_source.referral_type'
        ],
    );

    # use ReferrerDepartment - easier to retrieve data from object:
    my $practices = LIMS::DB::ReferrerDepartment::Manager
        ->get_referrer_department(@args); # warn Dumper $practices;

    my @data = map { # warn Dumper $_->parent_organisation->as_tree;
        [
           $_->referrer->name,
           $_->parent_organisation->referral_source->[0]->display_name,
           $_->parent_organisation->referral_source->[0]->organisation_code,
        ];
    } sort {
        $a->parent_organisation->referral_source->[0]->display_name
        cmp
        $b->parent_organisation->referral_source->[0]->display_name
    } @$practices;
    
    return \@data;
}

1;