package App::EzPz::UserStore;

use Module::Runtime qw(use_module);
use Scalar::Util 'blessed';
use Moo;

has ezmlm_config => (
  is => 'ro',
  coerce => sub {
    return $_[0] if blessed($_[0]);
    return use_module('App::EzPz::EzmlmConfig')->new($_[0]);
  }
);

has htpasswd_file => (is => 'ro', required => 1);

has _htpasswd => (is => 'lazy');

sub _build__htpasswd {
  my ($self) = @_;
  return use_module('Authen::Htpasswd')->new($self->htpasswd_file);
}

sub all {
  my ($self) = @_;
  return map $self->_inflate_user($_), $self->_htpasswd->all_users;
}

sub get {
  my ($self, $name) = @_;
  if (my $htp_user = $self->_htpasswd->lookup_user($name)) {
    return $self->_inflate_user($htp_user);
  } else {
    return undef;
  }
}

sub add {
  my ($self, $user) = @_;
  unless (blessed($user)) {
    $user = use_module('App::EzPz::User')->new($user);
  }
  my $htp_file = $self->_htpasswd;
  my $htp_user = $user->_htpasswd_user;
  $htp_file->add_user($htp_user);
  $htp_user->file($htp_file);
  $user->_set_ezmlm_config($self->ezmlm_config);
  return $user;
}

sub remove {
  my ($self, $user) = @_;
  $self->_htpasswd->remove_user($user->_htpasswd_user);
  return $user;
}

sub _inflate_user {
  my ($self, $htp_user) = @_;
  return use_module('App::EzPz::User')->new(
    htpasswd_user => $htp_user,
    ezmlm_config => $self->ezmlm_config,
  );
}

sub check_password {
  my ($self, $name, $password) = @_;
  return unless my $user = $self->get($name);
  return $user->check_password($password);
}

1;
