package leigh.m3;

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

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Objects;

public class MediaSegment {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(MediaSegment.class);
    private final String filename;
    private final String duration;
    private final M3U m3u;

    public MediaSegment(String filename, String duration, M3U m3u) {
        this.filename = filename;
        this.duration = duration;
        this.m3u = m3u;
    }

    public M3U getM3u() {
        return m3u;
    }

    public String getFilename() {
        return filename;
    }

    public String getUrlEncodedFilename() {
        return URLEncoder.encode(filename, Charset.defaultCharset());
    }

    public String getDuration() {
        return duration;
    }

    public long getDurationMs() {
        logger.info("Parsing duration: {}", duration);
        BigDecimal bs = new BigDecimal(duration);
        return bs.multiply(new BigDecimal(1000)).longValue();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MediaSegment that = (MediaSegment) o;
        return Objects.equals(filename, that.filename) && Objects.equals(duration, that.duration);
    }

    @Override
    public int hashCode() {
        return Objects.hash(filename, duration);
    }

    @Override
    public String toString() {
        return "MediaChunk{" +
                "filename=" + filename +
                ", duration=" + duration +
                '}';
    }
}
