package Tak::World;

use Tak::JSONChannel;
use Tak::ServiceManager;
use Tak::ModuleLoader;
use Tak::Router;
use Tak::Remote;

use Moo;

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

sub new_from_stdio {
  open my $stdin, '<&', \*STDIN;
  open my $stdout, '>&', \*STDOUT;
  shift->new(channel_args => { read_fh => $stdin, write_fh => $stdout });
}

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

sub _build_router {
  my ($self) = @_;
  my $channel = Tak::JSONChannel->new($self->channel_args);

  my $router = Tak::Router->new(
    channel => $channel
  );
  
  my $remote = Tak::Remote->new(
    router => $router,
    name => 'module_sender'
  );
  
  my $loader = Tak::ModuleLoader->new(
    remote => $remote
  );
  
  unshift @INC, $loader->inc_callback;
  
  return $router;
}

sub run { shift->router->run }
  
1;
