package code.name.monkey.retromusic.service

import android.animation.Animator
import android.animation.ValueAnimator
import android.media.MediaPlayer
import androidx.core.animation.doOnEnd
import code.name.monkey.retromusic.service.playback.Playback
import code.name.monkey.retromusic.util.PreferenceUtil

class AudioFader {
    companion object {

        @JvmStatic
        inline fun createFadeAnimator(
            fadeIn: Boolean /* fadeIn -> true  fadeOut -> false*/,
            mediaPlayer: MediaPlayer,
            crossinline endAction: (animator: Animator) -> Unit /* Code to run when Animator Ends*/
        ): Animator? {
            val duration = PreferenceUtil.crossFadeDuration * 1000
            if (duration == 0) {
                return null
            }
            val startValue = if (fadeIn) 0f else 1.0f
            val endValue = if (fadeIn) 1.0f else 0f
            return ValueAnimator.ofFloat(startValue, endValue).apply {
                this.duration = duration.toLong()
                addUpdateListener { animation: ValueAnimator ->
                    mediaPlayer.setVolume(
                        animation.animatedValue as Float, animation.animatedValue as Float
                    )
                }
                doOnEnd {
                    endAction(it)
                    // Set end values
                    mediaPlayer.setVolume(endValue, endValue)
                }
            }
        }

        @JvmStatic
        fun startFadeAnimator(
            playback: Playback,
            fadeIn: Boolean /* fadeIn -> true  fadeOut -> false*/,
            callback: Runnable /* Code to run when Animator Ends*/
        ) {
            val duration = PreferenceUtil.audioFadeDuration.toLong()
            if (duration == 0L) {
                callback.run()
                return
            }
            val startValue = if (fadeIn) 0f else 1.0f
            val endValue = if (fadeIn) 1.0f else 0f
            val animator = ValueAnimator.ofFloat(startValue, endValue)
            animator.duration = duration
            animator.addUpdateListener { animation: ValueAnimator ->
                playback.setVolume(
                    animation.animatedValue as Float
                )
            }
            animator.doOnEnd {
                callback.run()
            }
            animator.start()
        }
    }
}