package ru.micord.ervu.controller;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.kafka.common.utils.Bytes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import rtl.pgs.ervu.proto.ExtractRegistry;
import rtl.pgs.ervu.proto.ResponseData;
import ru.micord.ervu.dto.ExtractRequestDto;
import ru.micord.ervu.kafka.service.ReplyingKafkaService;
import ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil;

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

  private final ReplyingKafkaService<Object, Bytes> replyingKafkaService;

  @Value("${ervu.kafka.registry.extract.request.topic}")
  private String registryExtractRequestTopic;
  @Value("${ervu.kafka.registry.extract.reply.topic}")
  private String registryExtractReplyTopic;

  public ExtractController(ReplyingKafkaService<Object, Bytes> replyingKafkaService) {
    this.replyingKafkaService = replyingKafkaService;
  }

  @GetMapping(value = "/extract/{formatRegistry}")
  public ResponseEntity<Resource> getExtract(@PathVariable String formatRegistry) {
    String ervuId = SecurityUtil.getErvuId();

    if (ervuId == null) {
      return ResponseEntity.noContent().build();
    }
    ExtractRequestDto request = new ExtractRequestDto(ervuId, formatRegistry);
    byte[] reply = replyingKafkaService.sendMessageAndGetReply(registryExtractRequestTopic,
        registryExtractReplyTopic, request).get();

    try {
      ResponseData responseData = ResponseData.parseFrom(reply);
      ExtractRegistry extractRegistry = responseData.getDataRegistryInformation()
          .getExtractRegistry();
      String encodedFilename = URLEncoder.encode(extractRegistry.getFileName(), StandardCharsets.UTF_8);
      InputStreamResource resource = new InputStreamResource(extractRegistry.getFile().newInput());
      return ResponseEntity.ok()
          .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFilename)
          .contentType(MediaType.APPLICATION_OCTET_STREAM)
          .body(resource);
    }
    catch (InvalidProtocolBufferException e) {
      throw new RuntimeException("Failed to parse data", e);
    }
  }
}
