package be.iminds.ilabt.jfed.util.tmp_file_helpers;

import be.iminds.ilabt.jfed.util.IOUtils;
import be.iminds.ilabt.jfed.util.JFedUtils;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * TmpContentFile
 *
 * store any content temporarily
 */
public class TmpContentFile implements TmpFile {
    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(TmpContentFile.class);
    private static final AtomicLong globalFileNr = new AtomicLong(System.currentTimeMillis()); //we use date as start
    private final static String fixedRandom;
    static {
        String pName = ManagementFactory.getRuntimeMXBean().getName();
        Random rand = new Random(System.currentTimeMillis()+pName.hashCode());
        fixedRandom = ""+rand.nextLong();
    }

    private String content;
    private final File dir;
    private final File file;
    private final boolean assureUserOnlyPermissions;

    public TmpContentFile(String name, String ext, String content) {
        this(name, ext, content, false);
    }
    public TmpContentFile(String name, String ext, String content, boolean assureUserOnlyPermissions) {
        this.assureUserOnlyPermissions = assureUserOnlyPermissions;
        this.content = content;
        this.dir = new File(JFedUtils.getUserDataDirectory() + File.separator + "tmp");

        long currentFileNr = globalFileNr.getAndIncrement();
        this.file = new File(dir, name + fixedRandom+"-"+currentFileNr + (ext.startsWith(".") ? ext : "."+ext) );
    }

    @Override
    public void store() {
        //noinspection ResultOfMethodCallIgnored
        dir.mkdirs();
        IOUtils.stringToFile(file, content);
        if (assureUserOnlyPermissions)
            try {
                IOUtils.assureUserOnlyPerms(file, true, false, false);
            } catch (IOException e) {
                LOG.warn("Could not change file permissions to user only", e);
            }
        file.deleteOnExit(); //temp files should never remain after VM terminates.
        LOG.debug("stored file \"" + getFilename() + "\" exists=" + file.exists());
    }

    @Override
    public void delete() {
        LOG.debug("deleting file \"" + getFilename() + "\" exists=" + file.exists());
        try {
            //noinspection ResultOfMethodCallIgnored
            file.delete();
        } catch (Exception e) {
            LOG.error("Error deleting TmpContentFile \""+getFilename()+"\": "+e.getMessage(), e);
        }
    }

    @Override
    public File getFile() {
        return file;
    }

    @Override
    public File getDir() {
        assert Objects.equals(dir.getPath(), file.getParent());
        return dir;
    }

    @Override
    public String getFilename() {
        return file.getPath();
    }

    public String getContent() {
        return content;
    }
}
