package eu.eudat.logic.utilities.documents.pdf;

import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import org.apache.commons.io.IOUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

public class PDFUtils {

    public static File convertToPDF(FileEnvelope file, Environment environment) throws IOException {
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        String uuid = UUID.randomUUID().toString();
        map.add("files", new FileSystemResource(file.getFile()));
        map.add("filename", uuid + ".pdf");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("Content-disposition", "attachment; filename=" + uuid + ".pdf");
        headers.add("Content-type", "application/pdf");

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
                map, headers);

        byte[] queueResult = new RestTemplate().postForObject(environment.getProperty("pdf.converter.url") + "forms/libreoffice/convert"
                , requestEntity, byte[].class);

        File resultPdf = new File(environment.getProperty("temp.temp") + uuid + ".pdf");
        FileOutputStream output = new FileOutputStream(resultPdf);
        IOUtils.write(queueResult, output);
        output.close();
        Files.deleteIfExists(file.getFile().toPath());

        return resultPdf;
    }
}
