package ru.micord.ervu.kafka.controller;

import java.time.ZonedDateTime;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;

import com.fasterxml.jackson.databind.ObjectMapper;
import ervu.client.fileupload.WebDavClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.micord.ervu.audit.constants.AuditConstants;
import ru.micord.ervu.audit.service.AuditService;
import ru.micord.ervu.kafka.exception.ExcerptException;
import ru.micord.ervu.kafka.exception.ExcerptResponseException;
import ru.micord.ervu.kafka.model.Data;
import ru.micord.ervu.kafka.model.ExcerptResponse;
import ru.micord.ervu.kafka.service.ReplyingKafkaService;
import ru.micord.ervu.security.webbpm.jwt.UserIdsPair;
import ru.micord.ervu.security.webbpm.jwt.util.SecurityUtil;
import ru.micord.ervu.util.UrlUtils;

/**
 * @author Eduard Tihomirov
 */
@RestController
public class ErvuKafkaController {

  @Autowired
  private ReplyingKafkaService replyingKafkaService;

  @Autowired
  private AuditService auditService;

  @Autowired
  private WebDavClient webDavClient;

  @Value("${ervu.kafka.excerpt.reply.topic}")
  private String requestReplyTopic;

  @Value("${ervu.kafka.excerpt.request.topic}")
  private String requestTopic;

  @Autowired
  private ObjectMapper objectMapper;

  @RequestMapping(value = "/kafka/excerpt")
  public ResponseEntity<Resource> getExcerptFile(HttpServletRequest request) {
    String fileUrl = null;
    String fileName = null;
    long fileSize = 0;
    try {
      String clientTimeZone = request.getHeader("Client-Time-Zone");
      UserIdsPair userIdsPair = SecurityUtil.getUserIdsPair();
      Data data = new Data();
      data.setErvuId(userIdsPair.getErvuId());
      data.setPrnOid(userIdsPair.getEsiaUserId());
      String offset = ZonedDateTime.now(TimeZone.getTimeZone(clientTimeZone).toZoneId())
          .getOffset().getId();
      data.setTimeZone(offset);
      String kafkaResponse = replyingKafkaService.sendMessageAndGetReply(requestTopic,
          requestReplyTopic, objectMapper.writeValueAsString(data));
      ExcerptResponse excerptResponse = objectMapper.readValue(kafkaResponse, ExcerptResponse.class);

      if (!excerptResponse.getSuccess()) {
        throw new ExcerptResponseException(
            "Error with getting excerpt url " + excerptResponse.getMessage());
      }
      else if (excerptResponse.getData() == null || excerptResponse.getData().getFileUrl() == null
               || excerptResponse.getData().getFileUrl().isEmpty()) {
        auditService.processDownloadEvent(request, fileSize, fileName, 1,
            AuditConstants.FAILURE_STATUS_TYPE, fileUrl
        );
        return ResponseEntity.noContent().build();
      }
      fileUrl = excerptResponse.getData().getFileUrl();
      fileName = UrlUtils.extractFileNameFromUrl(excerptResponse.getData().getFileUrl());
      ResponseEntity<Resource> responseEntity = webDavClient.webDavDownloadFile(fileUrl);
      fileSize = responseEntity.getHeaders().getContentLength();
      auditService.processDownloadEvent(request, fileSize, fileName, 1,
          AuditConstants.SUCCESS_STATUS_TYPE, fileUrl
      );
      return responseEntity;
    }
    catch (Exception e) {
      auditService.processDownloadEvent(request, fileSize, fileName, 1,
          AuditConstants.FAILURE_STATUS_TYPE, fileUrl
      );
      throw new ExcerptException(e);
    }
  }
}
