package com.soundapp.soundgags.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.ad.tradpluslibrary.TPAdManager.showTPAD
import com.soundapp.soundgags.setting.SetUtil
import com.soundapp.soundgags.R
import com.soundapp.soundgags.setting.TypeAdapter
import com.soundapp.soundgags.datame.Reflection
import com.soundapp.soundgags.datame.MainViewModel
import com.soundapp.soundgags.setting.LikeUpClickListener
import com.soundapp.soundgags.setting.TimerThisListener
import com.bumptech.glide.Glide
import com.soundapp.soundgags.databinding.ActivityNoPlayingBinding
import com.soundapp.soundgags.setting.ClockChooseFragment
import com.soundapp.soundgags.setting.TopBarUtils
import java.io.IOException

class NowPlayingActivity : AppCompatActivity(), LikeUpClickListener,
    TimerThisListener {
    private lateinit var binding: ActivityNoPlayingBinding
    private lateinit var data: Reflection
    private lateinit var viewModel: MainViewModel
    private var mediaPlayer: MediaPlayer? = null
    private var countDownTimer: CountDownTimer? = null
    private lateinit var popView: ClockChooseFragment
    private lateinit var volumeReceiver: BroadcastReceiver

    companion object {
        const val KEY_LIST_DATA = "list_data"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TopBarUtils.setStatusBar(this.window)
        TopBarUtils.setLightStatusBar(this.window, true)
        binding = ActivityNoPlayingBinding.inflate(layoutInflater)
        data = intent.getParcelableExtra(KEY_LIST_DATA)!!
        setContentView(binding.root)
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        popView = ClockChooseFragment(this, this)
        showTPAD(this) {}
        initView()
        initAudio()
        initClick()
        setVolumeReceiver()

    }

    private fun setVolumeReceiver() {
        volumeReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if (intent.action == "android.media.VOLUME_CHANGED_ACTION") {
                    val audioManager =
                        context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
                    val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                    if (binding.seekbar.progress != currentVolume) {
                        binding.seekbar.progress = currentVolume
                    }
                }
            }
        }

        val filter = IntentFilter("android.media.VOLUME_CHANGED_ACTION")
        registerReceiver(volumeReceiver, filter)
    }

    private fun initClick() {
        //播放按钮
        binding.layoutPlay.setOnClickListener {
            showTPAD(this) {
                val playing = binding.playing.isVisible
                if (playing) {
                    if (mediaPlayer?.isPlaying == true) {
                        mediaPlayer?.pause()
                        showLoading(1)
                    }
                } else {
                    if (!mediaPlayer?.isPlaying!!) {
                        mediaPlayer?.start()
                        showLoading(2)
                    }
                }
            }

        }
        //弹出倒计时
        binding.imTimer.setOnClickListener {
            showTPAD(this) {
                popView.showTop(binding.imTimer)
            }
        }
        //like
        binding.imLike.setOnClickListener {
            showTPAD(this) {
                val isSelected = binding.imLike.isSelected
                if (isSelected) {
                    viewModel.updateLikeStatus(data.name, false)
                } else {
                    viewModel.updateLikeStatus(data.name, true)
                }
                binding.imLike.isSelected = !isSelected

            }
        }

    }

    private fun initAudio() {
        showLoading(0)
        mediaPlayer = MediaPlayer()
        try {
            mediaPlayer?.reset()
            mediaPlayer?.setDataSource(data.audioUrl)
            mediaPlayer?.prepareAsync()
            mediaPlayer?.setOnPreparedListener { showLoading(1) }
            mediaPlayer?.setOnCompletionListener { showLoading(1) }
        } catch (ioException: IOException) {
            showLoading(0)
            Toast.makeText(this, "----------prepare fail", Toast.LENGTH_SHORT).show()
        }
    }

    private fun initView() {
        //设置音量
        SetUtil.setVolume(this, binding.seekbar)
        binding.title.text = data.name
        binding.back.setOnClickListener { finish() }
        binding.imLoop.setOnClickListener {
            binding.imLoop.setSelected(!binding.imLoop.isSelected)
            mediaPlayer!!.isLooping = binding.imLoop.isSelected
        }
        val convert = data.convert
        if (convert.isEmpty()) {
            Glide.with(this).load(R.drawable.pic_only_diy)
                .into(binding.imgRecord)
        } else {
            Glide.with(this).load(data.convert).error(R.drawable.pic_only_diy)
                .placeholder(R.drawable.pic_only_diy)
                .into(binding.imgRecord)
        }

        val adapter = TypeAdapter()
        adapter.setListener(this)
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        //more
        viewModel.randomItems.observe(this@NowPlayingActivity) { randomItems ->
            // 更新UI
            Log.d("TAG", "initView: $randomItems")
            adapter.setList(randomItems, 1)
            adapter.notifyDataSetChanged()
        }
        viewModel.loadRandomItems()

//        like
        viewModel.checkLikeStatus(data.name, callback = { isLike ->
            run {
                binding.imLike.isSelected = isLike
            }
        })
//
    }

    private fun showLoading(type: Int) {
        when (type) {
            0 -> {//加载中
                binding.playLoading.visibility = View.VISIBLE
                binding.toPlay.visibility = View.GONE
                binding.playing.visibility = View.GONE
            }

            1 -> {//可播放
                binding.playLoading.visibility = View.GONE
                binding.toPlay.visibility = View.VISIBLE
                binding.playing.visibility = View.GONE
            }

            2 -> {//播放中
                binding.playLoading.visibility = View.GONE
                binding.toPlay.visibility = View.GONE
                binding.playing.visibility = View.VISIBLE
            }
        }
    }

    private fun stopCountDown() {
        countDownTimer?.cancel()

    }

    private fun startCountDown(time: Long) {
        stopCountDown()
        countDownTimer = object : CountDownTimer(time, 1000) {
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                popView.setOffSelected()
                binding.imTimer.isSelected = false
                if (!mediaPlayer?.isPlaying!!) {
                    showLoading(2)
                    mediaPlayer?.start()
                }
            }
        }
        countDownTimer?.start()
    }


    override fun onDestroy() {
        super.onDestroy()
        if (mediaPlayer?.isPlaying == true) {
            mediaPlayer?.stop()
        }
        mediaPlayer?.release()
        stopCountDown()
        if (::popView.isInitialized) {
            popView.hide()
        }
    }

    override fun onMoreClick(reflection: Reflection, isAdd: Boolean) {
        val intent = Intent(this, NowPlayingActivity::class.java)
        intent.putExtra(KEY_LIST_DATA, reflection)
        startActivity(intent)
        finish()

    }

    override fun onClickTimerListener(time: Long) {
        runOnUiThread {
            popView.hide()
            if (time == -1L) {
                Log.d("TAG", "onClickTimerListener: $time")
                binding.imTimer.isSelected = false
                stopCountDown()
            } else {
                binding.imTimer.isSelected = true
                startCountDown(time)
            }
        }

    }

}