package t::Util;

use strict;
use warnings;

use Exporter 'import';
our @EXPORT = qw(
   respond_json
   next_pending_not_events
   next_pending_events
   send_events

   matrix_login
   matrix_join_room
);

use HTTP::Response;
use JSON qw( encode_json );

use constant EVENTS_PATH => "/_matrix/client/api/v1/events";

sub respond_json
{
   my ( $p, $content ) = @_;

   $p->respond(
      HTTP::Response->new( 200, "OK", [ "Content-Type" => "application/json" ],
         encode_json $content
      )
   );
}

my $events_p;

sub next_pending_not_events
{
   my ( $ua ) = @_;

   while(1) {
      my $p = $ua->next_pending or return;
      my $req = $p->request;

      return $p if $req->method ne "GET" or
                   $req->uri->path ne EVENTS_PATH;

      die "Received a second /events request before the first finished" if $events_p;
      $events_p = $p;
   }
}

sub next_pending_events
{
   my ( $ua ) = @_;

   if( $events_p ) {
      my $p = $events_p; undef $events_p;
      return $p;
   }

   my $p = $ua->next_pending;
   my $req = $p->request;

   return $p if $req->method eq "GET" and
                $req->uri->path eq EVENTS_PATH;

   die "Received a different request while waiting for an /events request";
}

my $next_event_token = 0;

sub send_events
{
   my ( $ua, @events ) = @_;

   respond_json( next_pending_events( $ua ), {
      start => $next_event_token,
      end   => $next_event_token + scalar @events,
      chunk => \@events,
   });

   $next_event_token += scalar @events;
}

sub matrix_login
{
   my ( $matrix, $ua ) = @_;

   my $login_f = $matrix->login(
      user_id => '@my-test-user:localserver.test',
      access_token => "0123456789ABCDEF",
   );

   respond_json( $ua->next_pending, {
      end      => "next_token_here",
      presence => [],
      rooms    => [],
   });

   $login_f->get;
}

sub matrix_join_room
{
   my ( $matrix, $ua, @initial_state ) = @_;

   my $join_f = $matrix->join_room( "!room:localserver.test" );

   my $p = next_pending_not_events( $ua );
   respond_json( $p, { room_id => "!room:localserver.test" } );

   $p = next_pending_not_events( $ua );
   respond_json( $p, \@initial_state );

   return $join_f->get;
}

0x55AA;
