package dev.fyloz.trial.colorrecipesexplorer.web.controller.thymeleaf.files;

import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityNotFoundException;
import dev.fyloz.trial.colorrecipesexplorer.service.files.SimdutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.CLOSE_TAB;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.SIMDUT_FILES;

@Controller
@Profile("thymeleaf")
public class SimdutFilesController {

    private SimdutService simdutService;

    @Autowired
    public SimdutFilesController(SimdutService simdutService) {
        this.simdutService = simdutService;
    }

    @GetMapping(SIMDUT_FILES)
    public ResponseEntity<byte[]> getFile(HttpServletRequest request, @PathVariable Long id) {
        HttpHeaders headers = new HttpHeaders();

        try {
            if (simdutService.exists(id)) {
                byte[] simdutContent = simdutService.read(id);
                headers.setContentType(MediaType.APPLICATION_PDF);
                return new ResponseEntity<>(simdutContent, headers, HttpStatus.OK);
            } else {
                headers.add("Location", "/" + CLOSE_TAB);
            }
        } catch (EntityNotFoundException ex) {
            headers.add("Location", request.getHeader("referer"));
        }

        return new ResponseEntity<>(headers, HttpStatus.FOUND);
    }

    @PostMapping(SIMDUT_FILES)
    public ResponseEntity<Void> getFile(@PathVariable Long id) {
        try {
            return ResponseEntity.status(simdutService.exists(id) ? HttpStatus.OK : HttpStatus.NOT_FOUND).build();
        } catch (EntityNotFoundException ex) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
}
