package com.various.funny.sounds.audio.ui.activity

import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.applovin.mediation.MaxAd
import com.applovin.mediation.ads.MaxInterstitialAd
import com.bumptech.glide.Glide
import com.various.funny.sounds.audio.R
import com.various.funny.sounds.audio.data.NewBeanChild
import com.various.funny.sounds.audio.databinding.ActivityPlayBinding
import com.various.funny.sounds.audio.db.MyRoomBase
import com.various.funny.sounds.audio.helper.ComUtils
import com.various.funny.sounds.audio.max.MaxListener
import com.various.funny.sounds.audio.max.MaxManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException

class PlayActivity : AppCompatActivity(), View.OnClickListener {

    companion object {
        val INTENT_KEY_SOUND = "key_sound"
    }

    private lateinit var playBinding: ActivityPlayBinding

    private var mediaPlayer: MediaPlayer? = null

    private var isDownload = false
    private lateinit var listAds: List<MaxInterstitialAd>
    private lateinit var newBeanChild: NewBeanChild
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        listAds = MaxManager.loadAd(this@PlayActivity)
        playBinding = ActivityPlayBinding.inflate(layoutInflater)
        setContentView(playBinding.root)
        initStatusBar()
        newBeanChild = intent.getSerializableExtra(INTENT_KEY_SOUND) as NewBeanChild
        onInitView()
    }

    private fun initStatusBar() {
        val flags = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        window.decorView.systemUiVisibility = flags xor View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    }

    private fun onInitView() {
        playBinding.textviewSoundTitle.text = newBeanChild.title
        Glide.with(this).load(newBeanChild.preUrl).placeholder(R.mipmap.placeholder)
            .into(playBinding.imPreview)

        ComUtils.setPlayVolume(this, playBinding.volumeSeekbar)
        playBinding.imCollect.isSelected = newBeanChild.isCollect
        playBinding.iconBack.setOnClickListener(this)
        playBinding.imPlay.setOnClickListener(this)
        playBinding.imCollect.setOnClickListener(this)
        initMediaPlayer()
    }

    override fun onClick(v: View?) {
        when (v) {
            playBinding.imPlay -> {
                showAd()

            }

            playBinding.iconBack -> {
                finish()
            }

            playBinding.imCollect -> {
                playBinding.imCollect.isSelected = !playBinding.imCollect.isSelected
                CoroutineScope(Dispatchers.IO).launch {
                    MyRoomBase.dataBase.getNewBeanChildDao().updateData(newBeanChild.apply {
                        isCollect = playBinding.imCollect.isSelected
                    })
                }
            }
        }

    }

    private fun playAction() {
        if (isDownload) {
            playBinding.imPlay.isSelected = !playBinding.imPlay.isSelected
            play()
        } else {
            playBinding.progressbar.isVisible = true
            startDownload()
        }
    }

    private fun initMediaPlayer() {
        mediaPlayer = MediaPlayer()
        mediaPlayer?.isLooping = true
        newBeanChild.downloadUrl?.let {
            val file = File(it)
            if (file.exists()) {
                mediaPlayer?.reset()
                try {
                    mediaPlayer?.setDataSource(it)
                    mediaPlayer?.prepare()
                    isDownload = true
                } catch (ex: IOException) {
                    isDownload = false
                }

            } else {

                isDownload = false
            }

        }


    }

    private fun startDownload() {
        newBeanChild.mp3Url?.let {
            ComUtils.glideDownload(this, it) { file ->
                if (file == null) {
                    isDownload = false
                    playBinding.imPlay.isSelected = false
                    Toast.makeText(this@PlayActivity, getString(R.string.sorry), Toast.LENGTH_SHORT)
                        .show()
                    playBinding.progressbar.isVisible = false
                } else {
                    playBinding.progressbar.isVisible = false
                    file.absolutePath.let { path ->
                        mediaPlayer?.reset()
                        mediaPlayer?.setDataSource(path)
                        mediaPlayer?.prepare()
                        isDownload = true
                        playBinding.imPlay.isSelected = true
                        play()
                        CoroutineScope(Dispatchers.IO).launch {
                            MyRoomBase.dataBase.getNewBeanChildDao().updateData(newBeanChild.apply {
                                downloadUrl = path
                            })
                        }
                    }
                }


            }
        }
    }

    private fun play() {
        if (playBinding.imPlay.isSelected) {
            mediaPlayer?.start()
        } else {
            mediaPlayer?.pause()
        }
    }

    private fun showAd() {
        val checkCacheAd = MaxManager.checkCacheAd(listAds)
        if (checkCacheAd != null) {
            MaxManager.setMaxListener(checkCacheAd, object : MaxListener {
                override fun onFail(ad: MaxAd?) {
                    playAction()

                }

                override fun onSuccess() {

                }

                override fun onHidden() {
                    playAction()

                }

            })
            checkCacheAd.showAd()
        } else {
            playAction()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer?.stop()
        mediaPlayer?.release()
        mediaPlayer = null
    }

}