package com.example.exportmedia.audio

import com.example.exportmedia.MediaCallBack
import com.example.exportmedia.MediaHelper
import io.reactivex.Observable
import java.io.File

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

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

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

        arrayList.add("-i")
        s += "concat:"
        for (inputPath in inputFilePathArrayList) {
            s += inputPath
            if (inputFilePathArrayList.indexOf(inputPath) != inputFilePathArrayList.size - 1) {
                s += "|"
            }
        }
        arrayList.add(s)

        arrayList.add("-c")
        arrayList.add("copy")

        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() = AudioConcat(this)
    }
}