package ru.micord.ervu.controller;

import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.kafka.common.utils.Bytes;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import ru.micord.ervu.converter.SummonsResponseDataConverter;
import ru.micord.ervu.dto.SubpoenaRequestDto;
import ru.micord.ervu.dto.SubpoenaResponseDto;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RestController;
import proto.ervu.rp.summons.SummonsResponseData;
import ru.micord.ervu.kafka.service.ReplyingKafkaService;
import ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil;

/**
 * @author gulnaz
 */
@RestController
public class ErvuDataController {

  private final ReplyingKafkaService<Object, Bytes> replyingKafkaService;
  private final SummonsResponseDataConverter converter;

  @Value("${ervu.kafka.recruit.request.topic}")
  private String recruitRequestTopic;
  @Value("${ervu.kafka.recruit.reply.topic}")
  private String recruitReplyTopic;

  public ErvuDataController(
      @Qualifier("recruit") ReplyingKafkaService<Object, Bytes> replyingKafkaService,
      SummonsResponseDataConverter converter) {
    this.replyingKafkaService = replyingKafkaService;
    this.converter = converter;
  }

  @GetMapping(
      value = "/recruit",
      produces = MediaType.APPLICATION_JSON_VALUE
  )
  public SubpoenaResponseDto getData() {
    String ervuId = SecurityUtil.getErvuId();

    if (ervuId == null) {
      return new SubpoenaResponseDto.Builder().build();
    }
    SubpoenaRequestDto subpoenaRequestDto = new SubpoenaRequestDto(ervuId);
    byte[] reply = replyingKafkaService.sendMessageAndGetReply(recruitRequestTopic,
        recruitReplyTopic, subpoenaRequestDto).get();

    try {
      SummonsResponseData responseData = SummonsResponseData.parseFrom(reply);
      return converter.convert(responseData);
    }
    catch (InvalidProtocolBufferException e) {
      throw new RuntimeException("Failed to parse data", e);
    }
  }
}
