package LIMS::Model::Notification;

use Moose;
extends 'LIMS::Model::Base';

use Data::Dumper;

#-------------------------------------------------------------------------------
sub register_contact { # also does updates using insert_or_update_on_duplicate_key
    my ($self, $ref) = @_; # warn Dumper $ref;
    my $user_profile = $self->user_profile;

    my $active = $ref->{is_active};
    my $status = $ref->{status} || undef; # optional - not supplied on 1st input
    my $gmc    = $ref->{gmc};

    my $name = join ' ', map ucfirst $user_profile->{$_},
        qw/first_name last_name/;
    my $addr = $user_profile->{email};
    my %h = (
        contact_address => $addr,
        identifier      => $gmc,
        status          => $status, # uses table default value if null
        is_active       => $active,
        type            => 'referrer',
        name            => $name,
    ); # warn Dumper \%h;

    eval {
        my $o = LIMS::DB::ReportNotification->new(%h);
        $o->insert_or_update_on_duplicate_key;
    };
    return $@ if $@;
}

#-------------------------------------------------------------------------------
sub get_gmc_entry { # can't use RDBO - have unique key = name + identifier + contact_address
    my ($self, $gmc) = @_;

     my $contact = $self->lims_dbix->select('report_notification',
        ['name','status','is_active'], { identifier => $gmc })->hash;
    return $contact;
}

#-------------------------------------------------------------------------------
sub get_contact { # by id:
    my ($self, $id) = @_;
    my $o = LIMS::DB::ReportNotification
        ->new(id => $id)->load(with => 'department');
    my $data = $o->as_tree;
    # need to get location display, ref_src if hospital or parent if organisation:
    my $location_id = $o->identifier;
    if ( $o->type eq 'hospital' ) {
        my $location = LIMS::DB::ReferralSource->new(id => $location_id)->load;
        $data->{location} = $location->display_name;
    }
    elsif ( $o->type eq 'organisation' ) {
        my $parent = LIMS::DB::ParentOrganisation->new(id => $location_id)->load;
        $data->{location} = $parent->description;
    }
    return $data;
}

#-------------------------------------------------------------------------------
sub get_all_contacts {
    my $self = shift;
    my @args = ( with_objects => 'department', sort_by => ['type','name'] );
    my $o = LIMS::DB::ReportNotification::Manager->get_objects(@args);
    return $o;
}

# ------------------------------------------------------------------------------
sub update_contact {
	my ($self, $data) = @_; # warn Dumper $data;

    my %args = ( class => 'ReportNotification', data  => $data );
    return $self->update_object(\%args);
}

1;
