package com.example.exportmedia

import android.media.MediaMetadataRetriever
import io.reactivex.Observable
import java.io.File

class AudioLooper(
        private val mediaHelper: MediaHelper,
        private val loopCount: Int,
        private val loopAudioFile: File?,
        private val loopDuration: String
) {

    private constructor(builder: AudioLooper.Builder) : this(
            builder.mediaHelper,
            builder.loopCount,
            builder.loopAudioFile,
            builder.getTotalDuration()
    )

    fun output(file: File): Observable<String> {
        return Observable.create {
            mediaHelper.execute(arrayOf(
                    "-stream_loop", "$loopCount",
                    "-i", loopAudioFile!!.path,
                    "-t", loopDuration,
                    "-c", "copy",
                    "-y", file.path
            ), object : MediaCallBack {
                override fun onExecuteSuccess(message: String?) {
                    message?.let { it1 -> it.onNext(it1) }
                }

                override fun onExecuteFailed(message: String?) {
                    it.onError(Throwable(message))
                }

                override fun onExecuteFinish() {
                    it.onComplete()
                }
            })
        }
    }

    class Builder(internal val mediaHelper: MediaHelper) {
        var loopAudioFile: File? = null
            set(value) {
                field = value
                val mediaMetadataRetriever = MediaMetadataRetriever()
                mediaMetadataRetriever.setDataSource(value?.path)
                sourceDuration = (mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)).toInt()
            }

        var loopDuration: Int = 0 //mSec
            set(value) {
                field = value
                loopCount = value / sourceDuration + 1
                loopRemainderDuration = value % sourceDuration
            }

        internal var loopCount: Int = 0

        private var sourceDuration: Int = 0

        private var loopRemainderDuration: Int = 0

        internal fun getTotalDuration(): String {
            val totalDuration = (sourceDuration * loopCount + loopRemainderDuration) / 1000
            return String.format("%02d:%02d:%02d", totalDuration / 3600, (totalDuration % 3600) / 60, (totalDuration % 60))
        }

        fun build() = AudioLooper(this)
    }
}