package ctbrec.recorder.download;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;

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

import ctbrec.Config;
import ctbrec.OS;
import ctbrec.Recording;
import ctbrec.io.StreamRedirectThread;

public abstract class AbstractDownload implements Download {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractDownload.class);

    protected Instant startTime;

    protected void runPostProcessingScript(Recording recording) throws IOException, InterruptedException {
        String postProcessing = Config.getInstance().getSettings().postProcessing;
        if (postProcessing != null && !postProcessing.isEmpty()) {
            File target = recording.getAbsoluteFile();
            Runtime rt = Runtime.getRuntime();
            String[] args = new String[] {
                    postProcessing,
                    target.getParentFile().getAbsolutePath(),
                    target.getAbsolutePath(),
                    getModel().getName(),
                    getModel().getSite().getName(),
                    Long.toString(recording.getStartDate().getEpochSecond())
            };
            if(LOG.isDebugEnabled()) {
                LOG.debug("Running {}", Arrays.toString(args));
            }
            Process process = rt.exec(args, OS.getEnvironment());
            // TODO maybe write these to a separate log file, e.g. recname.ts.pp.log
            Thread std = new Thread(new StreamRedirectThread(process.getInputStream(), System.out));
            std.setName("Process stdout pipe");
            std.setDaemon(true);
            std.start();
            Thread err = new Thread(new StreamRedirectThread(process.getErrorStream(), System.err));
            err.setName("Process stderr pipe");
            err.setDaemon(true);
            err.start();

            int exitCode = process.waitFor();
            LOG.debug("Process finished with exit code {}", exitCode);
            if (exitCode != 0) {
                throw new ProcessExitedUncleanException("Post-Processing finished with exit code " + exitCode);
            }
        }
    }

    @Override
    public Instant getStartTime() {
        return startTime;
    }
}
