package com.design.mischiefgo.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.design.mischiefgo.ut.CommonUtil
import com.design.mischiefgo.R
import com.design.mischiefgo.ut.RandomAdapter
import com.design.mischiefgo.entity.Duplicate
import com.design.mischiefgo.entity.MainViewModel
import com.design.mischiefgo.ut.OnMoreClickListener
import com.design.mischiefgo.ut.SoundListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.design.mischiefgo.databinding.ActivityUseSoundBinding
import com.design.mischiefgo.ut.ChooseTimeFragment
import com.design.mischiefgo.ut.EvenTopUtils
import java.io.IOException

class UseSoundActivity : AppCompatActivity(), OnMoreClickListener,
    SoundListener {
    private lateinit var binding: ActivityUseSoundBinding
    private lateinit var data: Duplicate
    private lateinit var viewModel: MainViewModel
    private var mediaPlayer: MediaPlayer? = null
    private var countDownTimer: CountDownTimer? = null
    private lateinit var popView: ChooseTimeFragment
    private lateinit var volumeReceiver: BroadcastReceiver

    companion object {
        const val KEY_LIST_DATA = "list_data"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EvenTopUtils.setStatusBar(this.window)
        EvenTopUtils.setLightStatusBar(this.window, true)
        binding = ActivityUseSoundBinding.inflate(layoutInflater)
        data = intent.getParcelableExtra(KEY_LIST_DATA)!!
        setContentView(binding.root)
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        popView = ChooseTimeFragment(this, 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 {
            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 {
            popView.showTop(binding.imTimer)
        }
        //like
        binding.imLike.setOnClickListener {
            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() {
        //设置音量
        CommonUtil.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.music_default_copy).transform(CircleCrop())
                .into(binding.imgRecord)
        } else {
            Glide.with(this).load(data.convert).error(R.drawable.music_default_copy)
                .placeholder(R.drawable.music_default_copy).transform(CircleCrop())
                .into(binding.imgRecord)
        }

        val adapter = RandomAdapter()
        adapter.setListener(this)
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        //more
        viewModel.randomItems.observe(this@UseSoundActivity) { 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(duplicate: Duplicate) {
        val intent = Intent(this, UseSoundActivity::class.java)
        intent.putExtra(KEY_LIST_DATA, duplicate)
        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)
            }
        }

    }

}