package com.ray650128.gstreamer_demo_app.extensions

import android.util.Log
import com.ray650128.gstreamer_demo_app.model.Device

/**
 * IpCam 擴充函式-取得完整串流路徑
 * @param streamPathNum 串流路徑編號
 * @author Raymond Yang
 */
fun Device.getStreamPath(streamPathNum: Int): String? {
    val stringBuilder = getPath(this) ?: return null

    // 加入串流路徑
    when (streamPathNum) {
        1 -> if (this.stream1.isNotEmpty()) {
            if (this.stream1.first() != '/') {
                stringBuilder.append("/")
            }
            stringBuilder.append(this.stream1)
        }
        2 -> if (this.stream2.isNotEmpty()) {
            if (this.stream2.first() != '/') {
                stringBuilder.append("/")
            }
            stringBuilder.append(this.stream2)
        }
        else -> return null
    }
    Log.d("+++URL", stringBuilder.toString())
    return stringBuilder.toString()
}

private fun getPath(ipCam: Device): StringBuilder? {
    if (ipCam.ip.isEmpty()) return null
    val stringBuilder = StringBuilder()
    // 加入 URL schema
    stringBuilder.append("rtsp://")

    // 加入帳號密碼
    if (ipCam.account.isNotEmpty()) {
        if (ipCam.password.isEmpty()) {
            stringBuilder.append("${ipCam.account}@")
        } else {
            stringBuilder.append("${ipCam.account}:${ipCam.password}@")
        }
    }

    // 加入 IP 及 port
    stringBuilder.append(ipCam.ip)
    if (ipCam.rtspPort.isNotEmpty()) {
        stringBuilder.append(":${ipCam.rtspPort}")
    }
    return stringBuilder
}
