package Tak::Daemon::DaemonService;

use POSIX;
use Log::Contextual ();
use Log::Contextual::SimpleLogger;
use Tak::Router;
use Moo;

with 'Tak::Role::Service';

has 'set_done_cb' => (is => 'rw');

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

sub _build_router { Tak::Router->new }

sub handle_daemonize {
  my ($self) = @_;
  fork and exit;
  POSIX::setsid or die "Couldn't setsid: $!";
  fork and exit;
  close STDERR;
  open STDERR, '>', '/dev/null' or die "Couldn't re-open stderr: $!";
  Log::Contextual::set_logger( # there's no NullLogger? I thought I wrote one
    Log::Contextual::SimpleLogger->new({ levels => [] })
  );
  return 'done';
}

sub handle_become_successor {
  my ($self) = @_;
  my $done;
  $self->set_done_cb(sub { $done = 1 });
  $Tak::STDIOSetup::Next = $Tak::STDIOSetup::Next = sub {
    my $x = $self; # close over
    $0 = 'tak-daemon-node';
    Tak->loop_until($done);
  };
  return 'done';
}

sub handle_shutdown {
  my ($self) = @_;
  $self->set_done_cb->();
  return 'done';
}

sub start_router_request {
  shift->router->start_request(@_);
}

sub receive_router {
  shift->router->receive(@_);
}

1;
