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

import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityNotFoundException;
import dev.fyloz.trial.colorrecipesexplorer.service.files.XlsService;
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 javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.ALL_RECIPES_XLS;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.RECIPE_XLS;

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

    private XlsService xlsService;

    @Autowired
    public XlsExporterController(XlsService xlsService) {
        this.xlsService = xlsService;
    }

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

        try {
            byte[] xlsContent = xlsService.generate(id);

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(xlsContent.length)
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(xlsContent);
        } catch (EntityNotFoundException ex) {
            headers.add(HttpHeaders.LOCATION, request.getHeader("referer"));
            return new ResponseEntity<>(headers, HttpStatus.FOUND);
        }
    }

    @GetMapping(value = ALL_RECIPES_XLS, produces = "application/zip")
    public ResponseEntity<byte[]> getAllXls() throws IOException {
        HttpHeaders headers = new HttpHeaders();

        byte[] allXlsContent = xlsService.generateForAll();

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(allXlsContent.length)
                .contentType(MediaType.parseMediaType("application/zip"))
                .body(allXlsContent);
    }

}
