package Tak::JSONChannel;

use JSON::PP qw(encode_json decode_json);
use IO::Handle;
use Scalar::Util qw(weaken);
use Moo;

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

sub BUILD { shift->write_fh->autoflush(1); }

sub read_message {
  my ($self) = @_;
  if (defined(my $line = readline($self->read_fh))) {
    if (my $unpacked = $self->_unpack_line($line)) {
      return $unpacked;
    }
  } else {
    return [ 'close', 'channel' ];
  }
}

sub _unpack_line {
  my ($self, $line) = @_;
  my $data = eval { decode_json($line) };
  unless ($data) {
    $self->write_message(mistake => invalid_json => $@||'No data and no exception');
    return;
  }
  unless (ref($data) eq 'ARRAY') {
    $self->write_message(mistake => message_format => "Not an ARRAY");
    return;
  }
  unless (@$data > 0) {
    $self->write_message(mistake => message_format => "Empty request array");
    return;
  }
  $data;
}

sub write_message {
  my ($self, @msg) = @_;
  my $json = eval { encode_json(\@msg) };
  unless ($json) {
    $self->_raw_write_message(
      encode_json(
        [ failure => invalid_message => $@||'No data and no exception' ]
      )
    );
    return;
  }
  $self->_raw_write_message($json);
}

sub _raw_write_message {
  my ($self, $raw) = @_;
#warn "Sending: ${raw}\n";
  print { $self->write_fh } $raw."\n";
}

1;
