package com.player.musicoo.activity

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import com.bumptech.glide.Glide
import com.player.musicoo.R
import com.player.musicoo.databinding.ActivityPrimaryBinding
import com.player.musicoo.fragment.ImportFragment
import com.player.musicoo.fragment.MoHomeFragment
import com.player.musicoo.fragment.SearchFragment
import com.player.musicoo.media.MediaControllerManager
import com.player.musicoo.util.LogTag.LogD
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select

class PrimaryActivity : MoBaseActivity() ,SearchFragment.SearchFragmentCancelClickListener{
    /**
     * musicResponsiveListItemRenderer
     * musicTwoRowItemRenderer
     */

    private lateinit var binding: ActivityPrimaryBinding
    private val mFragments: MutableList<Fragment> = ArrayList()
    private var currentIndex: Int = 0
    private var mCurrentFragment: Fragment? = null

    override suspend fun main() {
        binding = ActivityPrimaryBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
        initPlayerListener()

        onReceive()
    }

    private fun initView() {
        initClick()
        initFragment()
    }

    private fun initClick() {
        binding.homeBtn.setOnClickListener {
            updateBtnState(0)
            changeFragment(0)
        }
        binding.searchBtn.setOnClickListener {
            updateBtnState(1)
            changeFragment(1)
        }
        binding.importBtn.setOnClickListener {
            updateBtnState(2)
            changeFragment(2)
        }

        binding.playBlackBtn.setOnClickListener {
            if (meController != null) {
                if (meController.isPlaying) {
                    meController.pause()
                    updatePlayState(false)
                } else {
                    meController.play()
                    updatePlayState(true)
                }
                updateProgressState()
            }
        }

        binding.goDetailsBtn.setOnClickListener {
            val intent = Intent(this, MoPlayDetailsActivity::class.java)
            intent.putExtra(
                MoPlayDetailsActivity.PLAY_DETAILS_COME_FROM,
                PrimaryActivity::class.java
            )
            startActivity(intent)
        }
    }

    private fun initFragment() {
        mFragments.clear()
        mFragments.add(MoHomeFragment())
        val searchFragment = SearchFragment()
        searchFragment.setButtonClickListener(this)
        mFragments.add(searchFragment)
        mFragments.add(ImportFragment())
        updateBtnState(0)
        changeFragment(0)
    }

    private fun changeFragment(index: Int) {
        currentIndex = index
        val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (null != mCurrentFragment) {
            ft.hide(mCurrentFragment!!)
        }
        var fragment = supportFragmentManager.findFragmentByTag(
            mFragments[currentIndex].javaClass.name
        )
        if (null == fragment) {
            fragment = mFragments[index]
        }
        mCurrentFragment = fragment

        if (!fragment.isAdded) {
            ft.add(R.id.frame_layout, fragment, fragment.javaClass.name)
        } else {
            ft.show(fragment)
        }
        ft.commit()
    }

    private fun updateBtnState(index: Int) {
        binding.apply {
            homeImg.setImageResource(
                when (index) {
                    0 -> R.drawable.home_select_icon
                    else -> R.drawable.home_unselect_icon
                }
            )
            searchImg.setImageResource(
                when (index) {
                    1 -> {
                        binding.tabLayout.visibility = View.GONE
                        R.drawable.search_select_icon
                    }

                    else -> {
                        binding.tabLayout.visibility = View.VISIBLE
                        R.drawable.search_unselect_icon
                    }
                }
            )
            importImg.setImageResource(
                when (index) {
                    2 -> R.drawable.import_select_icon
                    else -> R.drawable.import_unselect_icon
                }
            )
        }
    }


    private suspend fun onReceive() {
        while (isActive) {
            select<Unit> {
                events.onReceive {
                    when (it) {
                        Event.ActivityOnResume -> {
                            activityOnResume()
                        }

                        else -> {}
                    }
                }
            }
        }
    }

    private fun activityOnResume() {
        if (meController != null && meController.mediaItemCount > 0 && meController.duration > 0) {
            binding.playingStatusLayout.visibility = View.VISIBLE
            updateInfoUi(meController.currentMediaItem)
        } else {
            binding.playingStatusLayout.visibility = View.GONE
        }
    }

    private fun initPlayerListener() {
        meController?.addListener(playerListener)
    }

    private val playerListener = object : Player.Listener {
        override fun onPositionDiscontinuity(
            oldPosition: Player.PositionInfo,
            newPosition: Player.PositionInfo,
            reason: Int
        ) {
            if (reason == Player.DISCONTINUITY_REASON_AUTO_TRANSITION) {
                updateInfoUi(meController?.currentMediaItem)
            }
        }

        override fun onPlaybackStateChanged(playbackState: Int) {
            LogD(TAG, "playbackState->$playbackState")
            updateProgressState()
            when (playbackState) {
                Player.STATE_READY -> {
                    if (meController != null) {
                        LogD(TAG, "meController.duration->${meController.duration}")
                        binding.progressBar.setMaxProgress(MediaControllerManager.getDuration())
                        val currentPosition = meController.currentPosition
                        binding.progressBar.setProgress(currentPosition)
                    }
                }

                else -> {}
            }

        }

        override fun onPlayWhenReadyChanged(
            playWhenReady: Boolean,
            reason: Int
        ) {
            updatePlayState(playWhenReady)
            updateProgressState()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        meController?.removeListener(playerListener)
    }

    private var backPressedTime: Long = 0
    private val backToast: Toast by lazy {
        Toast.makeText(baseContext, getString(R.string.exit_main_text), Toast.LENGTH_SHORT)
    }

    override fun onBackPressed() {
        if (currentIndex == 1) {//等于搜索返回响应先退回home
            changeFragment(0)
            updateBtnState(0)
        } else {
            if (backPressedTime + 2000 > System.currentTimeMillis()) {
                super.onBackPressed()
                backToast.cancel()
                return
            } else {
                backToast.show()
            }
            backPressedTime = System.currentTimeMillis()
        }
    }

    /**
     * 更新播放进度
     */
    private fun updateProgressState() {
        //判断是否ready与播放中，否则停止更新进度
        if (meController != null && meController.playbackState == Player.STATE_READY && meController.isPlaying) {
            updatePlayState(meController.isPlaying)
            progressHandler.removeCallbacksAndMessages(null)
            progressHandler.sendEmptyMessage(1)
        } else {
            progressHandler.removeCallbacksAndMessages(null)
        }
    }

    /**
     * 播放进度
     */
    private val progressHandler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            //判断是否ready与播放中，否则停止更新进度
            if (meController != null && meController.playbackState == Player.STATE_READY && meController.isPlaying) {
                val currentPosition = meController.currentPosition
                binding.progressBar.setProgress(currentPosition)
                sendEmptyMessageDelayed(1, 50)
            }
        }
    }

    private fun updatePlayState(b: Boolean) {
        if (b) {
            binding.playStatusImg.setImageResource(R.drawable.playing_black_icon)
        } else {
            binding.playStatusImg.setImageResource(R.drawable.play_black_icon)
        }
    }

    private fun updateInfoUi(mediaItem: MediaItem?) {
        if (mediaItem == null) {
            return
        }
        Glide.with(this@PrimaryActivity)
            .load(mediaItem.mediaMetadata.artworkUri)
            .into(binding.audioImg)

        binding.name.text = mediaItem.mediaMetadata.title
        binding.desc.text = mediaItem.mediaMetadata.artist
    }

    override fun onFragmentClick() {
        onBackPressed()
    }
}