package es.uv.saic.web;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import es.uv.saic.dto.PdfDTO;
import es.uv.saic.feign.DocumentClient;
import fr.opensagres.xdocreport.core.XDocReportException;

@Controller
public class DownloadController {

	@Autowired
	private DocumentClient dc;
	/*
	 * Download a file associated with a task instance
	 * @param model
	 * @param idInstanciaTasca The ID of the task instance
	 * @param response HttpServletResponse
	 * @return A FileSystemResource representing the file to download
	 */
	@GetMapping(value="/download/{fileName}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
	@ResponseBody
	public FileSystemResource download(Model model, @PathVariable("fileName") BigInteger idInstanciaTasca) throws IOException {	
		// Convert byte[] to FileSystemResource
		ResponseEntity<byte[]> response = dc.download(idInstanciaTasca);
		byte[] data = response.getBody();
		String fileName = response.getHeaders().getFirst("Content-Disposition").split("filename=")[1].replace("\"", "");

		Path tempFile = Files.createTempFile( "download-", "-" + fileName);
		Files.write(tempFile, data);
		tempFile.toFile().deleteOnExit();

		return new FileSystemResource(tempFile.toFile());
	}					

	// PARA BORRAR
	/*
	 * Download a document by its ID
	 * @param model
	 * @param idDocument The ID of the document to download
	 * @param response HttpServletResponse
	 * @return A FileSystemResource representing the document to download
	 */
	@GetMapping(value="/download/document/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
	@ResponseBody
	public FileSystemResource downloadDocument(Model model, @PathVariable("id") Integer idDocument) throws IOException {		
		ResponseEntity<byte[]> response = dc.downloadDocument(idDocument);
		byte[] data = response.getBody();
		String fileName = response.getHeaders().getFirst("Content-Disposition").split("filename=")[1].replace("\"", "");

		Path tempFile = Files.createTempFile( "download-", "-" + fileName);
		Files.write(tempFile, data);
		tempFile.toFile().deleteOnExit();

		return new FileSystemResource(tempFile.toFile());
	}

	/*
	 * Download a populated template for a given task instance
	 * @param model
	 * @param idTascai The ID of the task instance
	 * @param response HttpServletResponse
	 * @return A byte array representing the populated template to download
	 */
	@GetMapping(value="/download/template/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
	@ResponseBody 
	public FileSystemResource downloadTemplate(Model model, @PathVariable("id") BigInteger idTascai) throws IOException, XDocReportException {
		ResponseEntity<byte[]> response = dc.downloadTemplate(idTascai);
		byte[] data = response.getBody();
		String fileName = response.getHeaders().getFirst("Content-Disposition").split("filename=")[1].replace("\"", "");

		Path tempFile = Files.createTempFile( "download-", "-" + fileName);
		Files.write(tempFile, data);
		tempFile.toFile().deleteOnExit();

		return new FileSystemResource(tempFile.toFile());
	}

	/*
	 * Generate a PDF preview from provided content
	 * @param model
	 * @param content The content to convert to PDF
	 * @param idtascai Optional ID of the task instance for context
	 * @param response HttpServletResponse
	 */
	@PostMapping(value="/pdf/preview")
	@ResponseBody
	public byte[] downloadTemplatePdf(Model model,
			@RequestParam("content") String content, @RequestParam("idtascai") Optional<BigInteger> idtascai) throws IOException, InterruptedException {
		PdfDTO pdf = new PdfDTO(content, idtascai);
		return dc.downloadTemplatePdf(pdf);
	}
}
