package com.iqser.red.service.persistence.management.v1.processor.utils;

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

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class FileUtils {

    public String getTemporaryDirectory() {

        String tmpdir = System.getProperty("java.io.tmpdir");
        if (isWindows() && StringUtils.isNotBlank(tmpdir)) {
            return tmpdir;
        }
        return "/tmp";
    }


    private boolean isWindows() {

        return StringUtils.containsIgnoreCase(System.getProperty("os.name"), "Windows");
    }


    public File createTempFile(String filenamePrefix, String filenameSuffix) throws IOException {

        File tempFile = Files.createTempFile(filenamePrefix, filenameSuffix).toFile();
        setRWPermissionsOnlyForOwner(tempFile);

        return tempFile;
    }


    // We don't need to check the results of the permission setters below,
    // since we're manipulating a file we created ourselves.
    @SuppressWarnings("ResultOfMethodCallIgnored")
    private void setRWPermissionsOnlyForOwner(File tempFile) {

        try {
            // deny for all
            tempFile.setReadable(false);
            tempFile.setWritable(false);
            tempFile.setExecutable(false);
            // allow for owner
            tempFile.setReadable(true, true);
            tempFile.setWritable(true, true);
        } catch (SecurityException ex) {
            // This should never happen since we're creating a temp file ourselves.
            log.warn("Caught an exception during temp file creation.  This should not happend.  Check the code.", ex);
        }
    }


    public File createTempFile(byte[] content, String filenamePrefix, String filenameSuffix) throws IOException {

        File tempFile = Files.createTempFile(filenamePrefix, filenameSuffix).toFile();
        setRWPermissionsOnlyForOwner(tempFile);

        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            IOUtils.write(content, outputStream);
        }
        return tempFile;
    }

}
