package leigh.m3.util;

import leigh.mecha.exec.LocalExecutor;
import leigh.mecha.exec.ProcessExecution;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.UUID;

public class M3UtilApp {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(M3UtilApp.class);

    public static void main(String args[]) throws IOException {
        Path dir = Paths.get("/Volumes/cal326/m34");
        Files.walk(dir).forEach(paths -> {
            try {
                extractCover(paths.toFile());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public static void extractCover(File path) throws Exception {
        if (!path.toString().endsWith("m4a") || !path.isFile()) return;
        logger.info("Extracting cover art: {}", path);
        String songBaseName = FilenameUtils.getName(path.toString().replace(".m4a", ""));
        ArrayList<String> args = new ArrayList<>();
        args.add(path.toString());
        args.add("-b");
        args.add("-CoverArt");
        LocalExecutor e = new LocalExecutor();
        ProcessExecution pe = e.execute("exiftool", args);
        // Might be a PNG, who knows. Usually JPG so lets start there.
        File output = new File(songBaseName + ".jpg");
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output))) {
            IOUtils.copy(pe.getInputStream(), bos);
        }

        // If there was no cover art, we wound up with a 0 length file. Lets fix that now.

        if (output.length() == 0) output.delete();
    }

    public static void extractMeta(File path) throws Exception {
        if (!path.toString().endsWith("m4a") || !path.isFile()) return;
        String songBaseName = FilenameUtils.getName(path.toString().replace(".m4a", ""));
        ArrayList<String> args = new ArrayList<>();
        args.add(path.toString());
        args.add("-j");
        LocalExecutor e = new LocalExecutor();
        ProcessExecution pe = e.execute("exiftool", args);
        String result = pe.drainInput();

        File output = new File(songBaseName + ".json");
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output))) {
            bos.write(result.getBytes(StandardCharsets.UTF_8));
        }

        logger.info("Command result: {}", result);
    }

    public static void uuidName(File path) {
        if (!path.toString().endsWith("m4a") || !path.isFile()) return;
        UUID id = UUID.randomUUID();
        path.renameTo(new File(id + ".m4a"));
    }

    public static void segmentFile(File path) throws Exception {
        if (!path.toString().endsWith("m4a") || !path.isFile()) return;

        String songBaseName = FilenameUtils.getName(path.toString().replace(".m4a", ""));
        ArrayList<String> args = new ArrayList<>();
        args.add("-t");
        args.add("6");
        args.add("-start-segments-with-iframe");
        args.add("-i");
        args.add(songBaseName + ".m3u8");
        args.add("-B");
        args.add(songBaseName + "_");
        args.add(path.toString());

        LocalExecutor e = new LocalExecutor();
        ProcessExecution pe = e.execute("mediafilesegmenter", args);
        String result = pe.drainInput();
        logger.info("Command result: {}", result);
    }
}
