package com.bomostory.sceneeditmodule.utils

import android.media.MediaPlayer

class MusicPlayer {
    private var musicPaths = ArrayList<String>()
    private var mediaPlayers = ArrayList<MediaPlayer>()

    fun add(path: String) {
        musicPaths.add(path)
    }

    fun remove(path: String){
        musicPaths.remove(path)
    }

    fun clear(){
        musicPaths.clear()
    }

    fun play() {
        prepare()
        for (mediaPlayer in mediaPlayers) {
            mediaPlayer.apply {
                prepareAsync()
            }
        }
    }

    private fun prepare() {
        mediaPlayers.clear()

        for (path in musicPaths) {
            val mediaPlayer = MediaPlayer()
            mediaPlayer.apply {
                reset()
                setDataSource(path)
                setOnPreparedListener {
                    it.start()
                }
            }
            mediaPlayers.add(mediaPlayer)
        }
    }

    fun start(){
        for (mediaPlayer in mediaPlayers) {
            mediaPlayer.apply {
                start()
            }
        }
    }

    fun pause(){
        for(mediaPlayer in mediaPlayers){
            mediaPlayer.pause()
        }
    }

    fun seekTo(mSec:Int){
        for(mediaPlayer in mediaPlayers){
            mediaPlayer.seekTo(mSec)
        }
    }

    fun stop() {
        for (mediaPlayer in mediaPlayers) {
            mediaPlayer.apply {
                stop()
            }
        }
    }

    fun release() {
        for (mediaPlayer in mediaPlayers) {
            mediaPlayer.apply {
                release()
            }
        }
        mediaPlayers.clear()
    }
}