package Tak::MetaService;

use Tak::WeakClient;
use Log::Contextual qw(:log);
use Moo;

with 'Tak::Role::Service';

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

sub handle_pid {
  return $$;
}

sub handle_ensure {
  my $self = shift;
  my ($name) = @_;
  return "Already have ${name}" if $self->router->services->{$name};
  $self->handle_register(@_);
}

sub handle_register {
  my ($self, $name, $class, %args) = @_;
  (my $file = $class) =~ s/::/\//g;
  require "${file}.pm";
  my $router = $self->router;
  if (my $expose = delete $args{expose}) {
    foreach my $name (keys %$expose) {
      if (my ($svc, @rest) = @{$expose->{$name}}) {
        die "router has no service ${svc}"
          unless my $service = $router->services->{$svc};
        $args{$name} = Tak::Client->new(service => $service)
                                  ->curry(@rest);
      } else {
        $args{$name} = Tak::WeakClient->new(service => $router);
      }
    }
  }
  my $new = $class->new(\%args);
  $router->register($name => $new);
  return "Registered ${name}";
}

1;
