package App::EzPz::User;

use Module::Runtime qw(use_module);
use Moo;

has _htpasswd_user => (
  is => 'ro', init_arg => 'htpasswd_user', required => 1,
  handles => [ qw(username password check_password) ],
);

has ezmlm_bindir => (is => 'rwp');

around BUILDARGS => sub {
  my ($orig, $self) = (shift, shift);
  my $args = $self->$orig(@_);
  $args->{htpasswd_user} ||=
    use_module('Authen::Htpasswd::User')->new(
      delete @{$args}{qw(username password)}
    );
  return $args
};

sub list_names {
  my ($self) = @_;
  if (my $unsplit = ($self->_htpasswd_user->extra_info||[])->[0]) {
    return split /\s*,\s*/, $unsplit;
  } else {
    return ();
  }
}

sub set_list_names {
  my ($self, @names) = @_;
  my @extra = @{$self->_htpasswd_user->extra_info||[]};
  $extra[0] = join(', ', @names);
  $self->_htpasswd_user->extra_info(@extra);
  return;
}

sub add_list_name {
  my ($self, $name) = @_;
  my %names; @names{my @names = $self->list_names} = ();
  $self->set_list_names(@names, $name) unless exists $names{$name};
  return $name;
}

sub remove_list_name {
  my ($self, $name) = @_;
  my %names; @names{my @names = $self->list_names} = ();
  if (exists $names{$name}) {
    $self->set_list_names(grep !($_ eq $name), $self->list_names)
  }
  return $name;
}

1;
