package arez;

import java.util.ArrayList;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import static org.testng.Assert.*;

final class TestSpyEventHandler
  implements SpyEventHandler
{
  private final ArrayList<Object> _events = new ArrayList<>();
  /**
   * When ussing assertNextEvent this tracks the index that we are up to.
   */
  private int _currentAssertIndex;

  @Override
  public void onSpyEvent( @Nonnull final Object event )
  {
    _events.add( event );
  }

  /**
   * Assert Event exists in list and return it.
   */
  @Nonnull
  <T> T assertEvent( @Nonnull final Class<T> type )
  {
    for ( final Object event : _events )
    {
      if ( type.isInstance( event ) )
      {
        return type.cast( event );
      }
    }
    fail( "Unable to locate event of type " + type + " in event list " + _events );
    return null;
  }

  /**
   * Assert Event at index is of specific type and return it.
   */
  @Nonnull
  <T> T assertEvent( @Nonnull final Class<T> type, final int index )
  {
    assertTrue( eventCount() > index );
    final Object event = _events.get( index );
    assertTrue( type.isInstance( event ),
                "Expected event at index " + index + " to be of type " + type + " but is " +
                " of type " + event.getClass() + " with value " + event );
    return type.cast( event );
  }

  void assertEventCount( final int count )
  {
    assertEquals( eventCount(), count, "Actual events: " + _events );
  }

  /**
   * Assert "next" Event is of specific type.
   * Increment the next counter.
   */
  @Nonnull
  <T> T assertNextEvent( @Nonnull final Class<T> type )
  {
    final T event = assertEvent( type, _currentAssertIndex );
    _currentAssertIndex++;
    return event;
  }

  /**
   * Assert "next" Event is of specific type.
   * Increment the next counter, run action.
   */
  <T> void assertNextEvent( @Nonnull final Class<T> type, @Nonnull final Consumer<T> action )
  {
    final T event = assertEvent( type, _currentAssertIndex );
    _currentAssertIndex++;
    action.accept( event );
  }

  private int eventCount()
  {
    return _events.size();
  }
}

@@ -496,383 +496,8 @@
  %7D%0A%0A
-  /**%0A   * Assert Event exists in list and return it.%0A   */%0A  @Nonnull%0A  %3CT%3E T assertEvent( @Nonnull final Class%3CT%3E type )%0A  %7B%0A    for ( final Object event : _events )%0A    %7B%0A      if ( type.isInstance( event ) )%0A      %7B%0A        return type.cast( event );%0A      %7D%0A    %7D%0A    fail( %22Unable to locate event of type %22 + type + %22 in event list %22 + _events );%0A    return null;%0A  %7D%0A%0A
   /*

Remove unused method