package somecodes

import com.fasterxml.jackson.databind.ObjectMapper
import java.io.File

@Suppress("unused")
class Codes {
    private val objectMapper = ObjectMapper()
    companion object{

        fun ValidFile(s: String?) : Boolean {
            if (s!=null){
                if (ValidString(s)){
                    val ff = File(s)
                    return ff.isFile
                }
            }
            return false
        }

        fun ValidString(s : String?) : Boolean {
            return s != null && s.isNotEmpty() && s.isNotBlank()
        }

        /**
         * Codec header for Zello audio packet is base64 encoded string from {samplingrate (16 Little Endian), frames_per_packet, frame_size_ms}
         * @param samplingrate Sampling rate in Hz (e.g., 8000, 16000, 32000, etc.)
         * @param frames_per_packet Number of frames per packet (usually 1 or 2)
         * @param frame_size_ms Size of each frame in milliseconds (e.g., 20, 30, 40, etc.)
         */
        fun toCodecHeader(samplingrate: Int, frames_per_packet: Byte, frame_size_ms: Byte) : String{
            val xx = ByteArray(4)
            xx[0] = (samplingrate and 0xFF).toByte() // Little Endian
            xx[1] = ((samplingrate shr 8) and 0xFF).toByte()
            xx[2] = frames_per_packet
            xx[3] = frame_size_ms
            return java.util.Base64.getEncoder().encodeToString(xx)
        }

        fun fromCodecHeader(header: String) : Triple<Int, Byte, Byte>? {
            val decoded = java.util.Base64.getDecoder().decode(header)
            if (decoded.size != 4) return null
            val samplingrate = (decoded[0].toInt() and 0xFF) or ((decoded[1].toInt() and 0xFF) shl 8)
            val frames_per_packet = decoded[2]
            val frame_size_ms = decoded[3]
            return Triple(samplingrate, frames_per_packet, frame_size_ms)
        }
    }
}