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 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_diagnoses {
	my ($self, $vars) = @_; # warn Dumper $vars;

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

	my @args = (
		query => [
            name => { rlike => $vars->{name} },
            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_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 = shift;
	my $args = shift; # warn Dumper $args;

    my @query;
    if ( my $str = $args->{practice} ) { # warn Dumper $str;
        @query = ( 'referral_types.description' => 'practice' ); # restrict to practices
        push @query, $str =~ /[a-z]\d{5}/i # parent code search
            ? ( parent_code => $str )
            : ( description => { rlike => $str } );
    }
    else {
        my $organisation = $args->{organisation};
        @query = ( 'referral_types.description' => { ne => 'practice' } ); # skip practices
        unless ( length $organisation > 6 ) { # or triggers error on RDBO > 0.802
            push @query, ( description => { rlike => $organisation } );
        }
    } # warn Dumper \@query;
	
    my %args_for_search = (
        query   => \@query,
		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;