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_config => (
  is => 'rwp',
  handles => {
    _new_list_object => 'new_list_object'
  }
);

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 has_list_name {
  my ($self, $name) = @_;
  my %names; @names{my @names = $self->list_names} = ();
  return exists $names{$name};
}

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

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

sub get_list {
  my ($self, $name) = @_;
  return undef unless $self->has_list_name($name);
  return $self->_new_list_object({ list_name => $name });
}

1;
