package LIMS::Controller::Login;

use base 'LIMS::Base';

use Moose;
with (
	'LIMS::Controller::Roles::Resource',
);

has 'user_messages' => (
    traits  => ['Counter'],
    is      => 'ro',
    isa     => 'Num',
    default => 0,
    handles => {
        msg_counter => 'inc',
    }
);
__PACKAGE__->meta->make_immutable(inline_constructor => 0);

use LIMS::Local::Utils;
use Data::Dumper;

# this should not normally be called (ie/hmds/login), but just in case,
# load login.tt & display 'already logged in' message:
sub default : StartRunmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    return $self->tt_process();
}

sub logout : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    # tidy up:
    $self->authen->logout;
    $self->session_delete; # causes loss of any flash messages !!

    return $self->redirect( $self->query->url );
}

# redirection target if detected by authen->is_new_login:
sub hello : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    
    my $profile = $self->user_profile; # $self->debug($profile);
    
    # get users location from profile:
	my $user_location = $profile->{user_location}->{location_name};

    my $user_type = # is user internal or external?
        $user_location eq $self->cfg('settings')->{lab_name_abbreviation}
        ? 'internal'
        : 'external';
    $self->tt_params( user_type => $user_type );

    # if any user-to-user messages:
    if ( my $messages = $self->get_user_messages($profile->{id}) ) {
        $self->msg_counter(scalar @{ $messages->{outbound} });
        $self->msg_counter(scalar @{ $messages->{inbound}  });
        $self->tt_params( user_messages => $messages );
    }
    # if any admin-to-user messages:
    if ( my $messages = $self->get_admin_messages($user_location) ) {  
        $self->msg_counter(scalar @$messages);
        $self->tt_params( admin_messages => $messages );
    }
    
    # convert profile last_login date to DT:
    if ( my $last_login = $profile->{last_login} ) { # maybe 1st login
        my $dt = LIMS::Local::Utils::to_datetime_using_parsedate($last_login);
        $self->tt_params( last_login => $dt );
    }
   	{ # if region_code exists in user profile, get new/relapsed diagnoses:
        my $org_code = $profile->{user_location}->{region_code};
        if ( $user_type eq 'external' && $org_code ) { # not required for lab staff
            my $data = $self->new_and_relapsed_diagnoses($org_code);    
            $self->tt_params( results => $data->{results} );
        }
    } 

    # if any messages or require new/relapsed diagnosis list:
    return $user_type eq 'external' || $self->user_messages
        ? $self->tt_process()
        : $self->redirect( $self->query->url ); # no messages & doesn't require new diags 
}

1;
