package ervu_business_metrics.kafka.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ervu_business_metrics.config.KafkaEnabledCondition;
import ervu_business_metrics.model.sso.SessionStateResponse;
import ervu_business_metrics.service.SessionResponseHolder;
import exception.JsonParseException;
import org.springframework.context.annotation.Conditional;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author Adel Kalimullin
 */
@Component
@Conditional(KafkaEnabledCondition.class)
public class SessionResponseListener{
  private final ObjectMapper objectMapper;
  private final SessionResponseHolder holder;

  public SessionResponseListener(ObjectMapper objectMapper,
      SessionResponseHolder holder) {
    this.objectMapper = objectMapper;
    this.holder = holder;
  }

  @KafkaListener(id = "${kafka.session.group.id}", topics = "${kafka.sso.sessions.state.response}")
  public void listenKafkaSession(String kafkaMessage) {
    SessionStateResponse response;
    try {
      response = objectMapper.readValue(kafkaMessage, SessionStateResponse.class);
    }
    catch (JsonProcessingException e) {
      throw new JsonParseException(e);
    }
    holder.initIfAbsent(response.getRequestKey(), response.getTotal());
    if (response.getUserSessionInfo() != null) {
      holder.add(response.getRequestKey(), response.getUserSessionInfo());
    }
  }
}
