package com.sinch.android.rtc.sample.pstn

import android.content.Context
import android.content.res.AssetFileDescriptor
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.util.Log

class AudioPlayer(private val context: Context) {

    private val ringTone: AudioTrack by lazy {
        createOutgoingRingtone()
    }

    fun playOutgoingRingtone() {
        stopOutgoingRingtone()
        try {
            ringTone.play()
        } catch (e: Exception) {
            Log.e(TAG, "Could not play progress tone", e)
        }
    }

    fun stopOutgoingRingtone() {
        ringTone.stop()
    }

    private fun createOutgoingRingtone(): AudioTrack {
        val fd = context.resources.openRawResourceFd(R.raw.ring_tone)
        val length = fd.length.toInt()
        val audioTrack = AudioTrack(
            AudioManager.STREAM_VOICE_CALL, SAMPLE_RATE,
            AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, length,
            AudioTrack.MODE_STATIC
        )
        val data = ByteArray(length)
        readFileToBytes(fd, data)
        audioTrack.write(data, 0, data.size)
        audioTrack.setLoopPoints(0, data.size / 2, 30)
        return audioTrack
    }

    private fun readFileToBytes(fd: AssetFileDescriptor, data: ByteArray) {
        val inputStream = fd.createInputStream()
        var bytesRead = 0
        while (bytesRead < data.size) {
            val res = inputStream.read(data, bytesRead, data.size - bytesRead)
            if (res == -1) {
                break
            }
            bytesRead += res
        }
    }

    companion object {
        private val TAG = AudioPlayer::class.java.simpleName
        private const val SAMPLE_RATE = 16000
    }

}
