package de.dhbwstuttgart.server.packet;

import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.ISerialNode;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import java.util.List;
import org.java_websocket.WebSocket;

/**
 * A packet to send all calculated data from the unification algorithm back to the client
 */
public class UnifyResultPacket implements IServerToClientPacket {

  public SerialList<ISerialNode> results;
  public SerialMap keyStorage;
  public String futureId;

  public static UnifyResultPacket create(List<ResultSet> resultSets, String futureId) {
    UnifyResultPacket serialized = new UnifyResultPacket();
    KeyStorage keyStorage = new KeyStorage();
    serialized.results = SerialList.fromMapped(resultSets, resultSet -> resultSet.toSerial(keyStorage));
    serialized.keyStorage = keyStorage.toSerial(keyStorage);
    serialized.futureId = futureId;
    return serialized;
  }

  @JsonIgnore
  public List<ResultSet> getResultSet(UnifyContext context) {
    return this.results.assertListOfMaps().stream()
      .map(resultData -> ResultSet.fromSerial(resultData, context)).toList();
  }

  @JsonIgnore
  public void onHandle(WebSocket webSocket, SocketClient socketClient) {
    SocketClient.logger.info("Received unify result");
    socketClient.completeResponseFuture(futureId, this);
  }


}
