package com.example.exportmedia.audio

import com.example.exportmedia.MediaCallBack
import com.example.exportmedia.MediaHelper
import com.example.exportmedia.data.AudioSource
import java.io.File
import kotlin.collections.ArrayList

class AudioMixer(
        private val mediaHelper: MediaHelper,
        private val audioSourceList: ArrayList<AudioSource>) {

    lateinit var mediaCallBack: MediaCallBack

    private constructor(builder: Builder) : this(
            builder.mediaHelper,
            builder.audioSourceList
    )

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

        for (audioSource in audioSourceList) {
            arrayList.add("-i")
            arrayList.add("${audioSource.path}")
        }

        if (audioSourceList.size > 0) {
            var delayString = ""
            var mixString = ""

            arrayList.add("-filter_complex")
            for (audioSource in audioSourceList) {
                val inputStream = "[${audioSourceList.indexOf(audioSource)}]"
                if (audioSource.offsetSec > 0) {
                    val outputStream = "[a${audioSourceList.indexOf(audioSource)}]"
                    delayString += "${inputStream}adelay=${audioSource.offsetSec}$outputStream;"
                    mixString += outputStream
                } else {
                    mixString += inputStream
                }
            }
            arrayList.add("$delayString${mixString}amix=inputs=${audioSourceList.size}[out]")
            arrayList.add("-map")
            arrayList.add("[out]")
            arrayList.add(file.path)

            mediaHelper.execute(arrayList.toTypedArray(), mediaCallBack)
        }
    }

    class Builder(internal val mediaHelper: MediaHelper) {

        var audioSourceList = ArrayList<AudioSource>()

        fun build() = AudioMixer(this)
    }
}