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';

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

    return $count;
}

#-------------------------------------------------------------------------------
sub check_storage_vialId { # just need to know if it exists:
    my ($self, $id) = @_;

    my $i = LIMS::DB::RequestStorage::Manager
        ->get_objects_count( query => [ vialId => $id ] );
    return $i; # will be 1 or 0
}

#-------------------------------------------------------------------------------
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 $vars = shift;

    # RfC594 - fix for unbalanced parens or square brackets:
	my $str = LIMS::Local::Utils::mysql_escape_parens($vars->{referrer_name}); # warn $str;

    my %args = (
		query => [
			'referral_sources.id' => $vars->{source_id},
			'referrers.name'      => { rlike => $str },
            'referrers.active'    => 'yes',
            'referrer_department.is_active' => 'yes',
		],
		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_diagnoses {
	my ($self, $vars) = @_; # warn Dumper $vars;

    my $diagnosis_id = $vars->{diagnosis_id} || 0; # in case inactive legacy

	# get str from $vars, escape left & right parentheses:
	my $str = LIMS::Local::Utils::mysql_escape_parens($vars->{name}); # warn $str;

	my @args = (
		query => [
            name => { rlike => $str },
            or   => [ active => 'yes', id => $diagnosis_id ], # include id if supplied
        ],
        require_objects => 'diagnostic_category',
		limit  => 10,
	);

	my $diagnoses = LIMS::DB::Diagnosis::Manager->get_diagnoses(@args);
	return $diagnoses;
}

#-------------------------------------------------------------------------------
sub get_user_by_username {
    my ($self, $str) = @_;

    my @query = ( username => { rlike => $str } );
    my $o = LIMS::DB::User::Manager->get_objects( query => \@query );
    return $o;
}

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

    my %args_for_query = (
        query   => [
            or => [
                organisation_code => { like => '%' . $args->{location} . '%' },
                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, $ref) = @_; # warn Dumper $ref;

	my $str = $ref->{practice} || $ref->{organisation};

	my $re = qr/
		\A(
			[A-Z]\d{5}|		# 5-digit practice code (B81093) OR
			[A-Z0-9]{3} 	# 3-char parent code (RR8, RNZ, etc)
		)\Z
	/x; # warn Dumper $re;

	# skip, or restrict to, practices:
	my $referral_type = $ref->{practice} ? 'practice' : { ne => 'practice' };

	my @query = ( $str =~ /$re/ )  # parent code search (RR8, B81093, RNZ, etc)
		? ( parent_code => $str )
		: (
			description => { rlike => $str },
			'referral_types.description' => $referral_type,
		); # warn Dumper \@query;

    my @args = (
		require_objects => 'referral_type',
        sort_by => 'description',
        query   => \@query,
        limit   => 10,
    );

    my $o = LIMS::DB::ParentOrganisation::Manager->get_objects(@args);
	return $o;
}

# ------------------------------------------------------------------------------
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;
