package com.airlock.iam.flow.shared.domain.model.matrix;

import com.airlock.iam.base.api.domain.model.mapification.MapifiedValues;
import com.airlock.iam.base.domain.model.mapification.MapifiedValuesBuilder;
import com.airlock.iam.core.misc.impl.authen.TanChallengeSession;
import com.airlock.iam.flow.api.domain.model.step.StepSession;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Optional;

public final class MatrixCheckingStepSession implements StepSession {
   private static final String SESSION_KEY = "session";
   private static final String CHALLENGE_KEY = "challenge";
   private final TanChallengeSession authenticationSession;
   private Optional<MatrixChallenge> currentChallenge = Optional.empty();

   public void updateChallenge(MatrixChallenge challenge) {
      this.currentChallenge = Optional.of(challenge);
   }

   public void clearChallenge() {
      this.currentChallenge = Optional.empty();
   }

   public boolean isExpectingResponseVerification() {
      return this.currentChallenge.isPresent();
   }

   @Override
   public MapifiedValues mapify() {
      return MapifiedValuesBuilder.mapifiedValues()
         .put("session", this.authenticationSession.mapify())
         .putIfPresent("challenge", this.currentChallenge.map(MatrixChallenge::mapify))
         .build();
   }

   public static MatrixCheckingStepSession demapify(MapifiedValues values) {
      return new MatrixCheckingStepSession(
         values.demapifyValue("session", TanChallengeSession::demapify), values.demapifyOptional("challenge", MatrixChallenge::demapify)
      );
   }

   @SuppressFBWarnings(justification = "generated code")
   public TanChallengeSession getAuthenticationSession() {
      return this.authenticationSession;
   }

   @SuppressFBWarnings(justification = "generated code")
   public Optional<MatrixChallenge> getCurrentChallenge() {
      return this.currentChallenge;
   }

   @SuppressFBWarnings(justification = "generated code")
   public MatrixCheckingStepSession(TanChallengeSession authenticationSession) {
      this.authenticationSession = authenticationSession;
   }

   @SuppressFBWarnings(justification = "generated code")
   private MatrixCheckingStepSession(TanChallengeSession authenticationSession, Optional<MatrixChallenge> currentChallenge) {
      this.authenticationSession = authenticationSession;
      this.currentChallenge = currentChallenge;
   }
}
