package us.shandian.giga.get

import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import org.schabi.newpipe.extractor.MediaFormat
import org.schabi.newpipe.extractor.stream.AudioStream
import org.schabi.newpipe.extractor.stream.DeliveryMethod
import org.schabi.newpipe.extractor.stream.Stream
import org.schabi.newpipe.extractor.stream.SubtitlesStream
import org.schabi.newpipe.extractor.stream.VideoStream
import java.io.Serializable

@Parcelize
class MissionRecoveryInfo(
    var format: MediaFormat,
    var desired: String? = null,
    var isDesired2: Boolean = false,
    var desiredBitrate: Int = 0,
    var kind: Char = Char.MIN_VALUE,
    var validateCondition: String? = null,
    var audioTrackId: String? = null,
    var isHls: Boolean = false,
    var isSabr: Boolean = false,
    var itag: Int = -1,
    var deliveryMethodInfo: Serializable? = null
) : Serializable, Parcelable {
    constructor(stream: Stream) : this(format = stream.getFormat()!!) {
        isHls = stream.getDeliveryMethod() == DeliveryMethod.HLS
        isSabr = stream.getDeliveryMethod() == DeliveryMethod.SABR
        deliveryMethodInfo = stream.deliveryMethodInfo
        when (stream) {
            is AudioStream -> {
                desiredBitrate = stream.averageBitrate
                isDesired2 = false
                kind = 'a'
                audioTrackId = stream.audioTrackId
                itag = stream.itag
            }
            is VideoStream -> {
                desired = stream.resolution
                isDesired2 = stream.isVideoOnly
                kind = 'v'
                audioTrackId = stream.audioTrackId
                itag = stream.itag
            }
            is SubtitlesStream -> {
                desired = stream.languageTag
                isDesired2 = stream.isAutoGenerated
                kind = 's'
            }
            else -> throw RuntimeException("Unknown stream kind")
        }
    }

    override fun toString(): String {
        val info: String
        val str = StringBuilder()
        str.append("{type=")
        when (kind) {
            'a' -> {
                str.append("audio")
                info = "bitrate=$desiredBitrate"
            }
            'v' -> {
                str.append("video")
                info = "quality=$desired videoOnly=$isDesired2"
            }
            's' -> {
                str.append("subtitles")
                info = "language=$desired autoGenerated=$isDesired2"
            }
            else -> {
                info = ""
                str.append("other")
            }
        }
        str.append(" format=")
            .append(format.getName())
            .append(' ')
            .append(info)
            .append('}')
        return str.toString()
    }
}
