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 receive {
  my ($self) = @_;
  while (my $line = readline($self->read_fh)) {
    if (my $unpacked = $self->_unpack_line($line)) {
      return $unpacked;
    }
  }
}

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

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

sub _raw_send {
  my ($self, $raw) = @_;
  print { $self->write_fh } $raw."\n";
}

1;
