package com.example.exportmedia

import io.reactivex.Observable
import java.io.File
import kotlin.collections.ArrayList

class AudioMuxer(
        private val mediaHelper2: MediaHelper,
        private val inputFilePathArrayList: ArrayList<String>
) {

    private constructor(builder: AudioMuxer.Builder) : this(
            builder.mediaHelper,
            builder.inputFilePathArrayList
    )

    fun output(file: File): Observable<String> {
        val arrayList = ArrayList<String>()

        for (inputFilePath in inputFilePathArrayList) {
            arrayList.add("-i")
            arrayList.add(inputFilePath)
        }

        arrayList.add("-filter_complex")
        arrayList.add("amix=inputs=${inputFilePathArrayList.size}:duration=longest:dropout_transition=0")
        arrayList.add("-y")
        arrayList.add(file.path)

        return Observable.create {
            mediaHelper2.execute(arrayList.toTypedArray()
                    , 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) {

        internal val inputFilePathArrayList = ArrayList<String>()

        fun addInputSource(file: File) {
            inputFilePathArrayList.add(file.path)
        }

        fun build() = AudioMuxer(this)
    }
}