package de.dhbwstuttgart.server;

import de.dhbwstuttgart.server.packet.IServerToClientPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class SocketFuture<T extends IServerToClientPacket> extends CompletableFuture<T> {

  public final String futureId = UUID.randomUUID().toString();

  public final List<Class<T>> allowedTriggers;

  public SocketFuture(List<Class<T>> allowedTriggers) {
    this.allowedTriggers = allowedTriggers;
  }

  public boolean accept(IServerToClientPacket trigger) {
    if (this.allowedTriggers.contains(trigger.getClass())) {
      this.complete((T)trigger);
      return true;
    }
    return false;
  }

  @Override
  public T get() {
    try {
      return super.get();
    }
    catch (InterruptedException | ExecutionException exception) {
      throw new RuntimeException(exception);
    }
  }

  /**
   * Special case where the future is immediately fulfilled without a response package similar to
   * <code>CompletableFuture.completedFuture()</code> but without a value
   */
  public static <R extends IServerToClientPacket> SocketFuture<R> completedFuture() {
    SocketFuture<R> dummyFuture = new SocketFuture<>(new ArrayList<>(0));
    dummyFuture.complete(null);
    return dummyFuture;
  }

}
