package leigh.m3;

import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;

/**
 * This class represents a M3U8 file. Within the context of the M3 service, it represents all the media segments
 * for a given media track. This class does not check to see if the media segments actually exist on disk.
 *
 * @author Alex Leigh
 */
public class M3U {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(M3U.class);
    private final ArrayList<MediaSegment> segments = new ArrayList<>();
    private final Path file;

    /**
     * Create a new M3U object from the given .m3u8 file located on disk. The file should have been generated
     * with Apple's mediafilesegmenter tool. Other files, while legal, MAY not parse if they do not contain
     * the bitrate information.
     */
    public M3U(Path file) throws IOException {
        this.file = file;
        try (BufferedReader br = new BufferedReader(new FileReader(file.toFile()))) {
            String line;
            int i = 0;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("#EXTINF:")) {
                    // We assume the file format is legal
                    String fn = br.readLine();
                    // Skip a line
                    fn = br.readLine();
                    String[] parse = line.split(":");
                    segments.add(new MediaSegment(fn, parse[1].replace(",", "").trim(), this));
                    i++;
                }
                logger.debug("Read line: {}", line);
            }
        }
    }

    @Override
    public String toString() {
        return "M3U{" +
                "chunks=" + segments +
                '}';
    }

    public Path getFile() {
        return file;
    }

    /**
     * Return all the segments associated with this media file.
     */
    public ArrayList<MediaSegment> getSegments() {
        return segments;
    }

    public static void main(String[] args) throws IOException {
        M3U m3u = new M3U(Path.of("music/[0ther]_Pendulum_Single_Pendulum.m3u8"));
        logger.info("m3u: {}", m3u);
    }
}
