package org.egl_cepgl.pm.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.egl_cepgl.pm.dto.FileDto;
import org.egl_cepgl.pm.model.File;
import org.egl_cepgl.pm.model.Procurement;
import org.egl_cepgl.pm.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Objects;

@Slf4j
@Api("api/files")
@RestController
@RequestMapping("api/files")
public class FileController
{
    private final FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @PostMapping(value = "/upload")
    public ResponseEntity<FileDto> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("file_category") Long file_category,
            @RequestParam("to_notify") Boolean to_notify
    ){
        Long category= null;
        if(file_category != null){
            category= file_category.longValue();
        }
        return ResponseEntity.ok(fileService.storeFile(file, category, to_notify));
    }

    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        Path filePath = fileService.loadFileAsResource(fileName);
        //Resource resource;
        InputStreamResource resource;
        try {
            //resource = filePath.toUri().toURL().openStream()::transferTo;
            java.io.File file = new java.io.File(String.valueOf(filePath));
            resource = new InputStreamResource(new FileInputStream(file));
        } catch (IOException ex) {
            throw new RuntimeException("File not found " + fileName, ex);
        }
        String contentType;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(Objects.requireNonNullElse(contentType, "application/octet-stream")))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(resource);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity delete(@PathVariable("id") Long id) {
        log.info("++++++++++++"+String.valueOf(id));
        fileService.delete(id);
        return ResponseEntity.ok().build();
    }
}
