package ctbrec.recorder.postprocessing;
import static ctbrec.io.IoUtils.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.Config;
import ctbrec.Recording;
import ctbrec.recorder.RecordingManager;

public class Move extends AbstractPlaceholderAwarePostProcessor {

    private static final Logger LOG = LoggerFactory.getLogger(Rename.class);
    public static final String PATH_TEMPLATE = "path.template";
    public static final String DEFAULT = "${modelSanitizedName}" + File.separatorChar + "${localDateTime}";

    @Override
    public String getName() {
        return "move";
    }

    @Override
    public void postprocess(Recording rec, RecordingManager recordingManager, Config config) throws IOException {
        String pathTemplate = getConfig().getOrDefault(PATH_TEMPLATE, DEFAULT);
        String path = fillInPlaceHolders(pathTemplate, rec, config);
        File src = rec.getPostProcessedFile();
        boolean isFile = src.isFile();
        File target = new File(path, src.getName());
        if (Objects.equals(src, target)) {
            return;
        }
        LOG.info("Moving {} to {}", src.getName(), target.getParentFile().getCanonicalPath());
        Files.createDirectories(target.getParentFile().toPath());
        Files.move(rec.getPostProcessedFile().toPath(), target.toPath());
        rec.setPostProcessedFile(target);
        if (Objects.equals(src, rec.getAbsoluteFile())) {
            rec.setAbsoluteFile(target);
        }
        rec.getAssociatedFiles().remove(src.getCanonicalPath());
        rec.getAssociatedFiles().add(target.getCanonicalPath());
        if (isFile) {
            deleteEmptyParents(src.getParentFile());
        } else {
            deleteEmptyParents(src);
        }
    }

    @Override
    public String toString() {
        String s = getName();
        if (getConfig().containsKey(PATH_TEMPLATE)) {
            s += " [" + getConfig().get(PATH_TEMPLATE) + ']';
        }
        return s;
    }
}
