package com.bassbooster.soundeffects.equalizer.view.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bassbooster.equalizer.R
import com.bassbooster.soundeffects.equalizer.adapter.VisualizerAdapter
import com.bassbooster.soundeffects.equalizer.data.model.MediaInfo
import com.bassbooster.soundeffects.equalizer.data.model.VisualizerModel
import com.bassbooster.equalizer.databinding.FragmentPlayBinding
import com.bassbooster.soundeffects.equalizer.event.MessageEvent
import com.bassbooster.soundeffects.equalizer.event.PlayAdsEvent
import com.bassbooster.soundeffects.equalizer.utils.SharedPreferencesUtil
import com.bassbooster.soundeffects.equalizer.view.MainActivity
import com.bassbooster.soundeffects.equalizer.viewmodel.MainViewModel
import com.bullhead.equalizer.ButtonController
import com.bullhead.equalizer.EqualizerFragment
import com.bullhead.equalizer.EqualizerToAppListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


class PlayFragment : Fragment() {
    private var visualizerAdapter: VisualizerAdapter? = null
    private var sessionId: Int = 0
    val ARG_AUDIO_SESSIOIN_ID = "audio_session_id"
    private var _binding: FragmentPlayBinding? = null
    private val binding get() = _binding!!
    var isCheck = true
    var mListType: ArrayList<String>? = null
    private lateinit var sharedPreferencesUtil: SharedPreferencesUtil
    var isPlayClick = true
    var isPauseClick = true
    var isSkipClick = true
    var isNextClick = true
    var musicAdsLoaded = false
//    private var mFirebaseAnalytics: FirebaseAnalytics? = null
//    private var nativeAdHelper: NativeAdHelper? = null

//    val adCallback = object : AperoAdCallback() {
//        override fun onAdClicked() {
//            super.onAdClicked()
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"Native_music_click","view ad tại màn Music","music_view")
//        }
//
//        override fun onAdImpression() {
//            super.onAdImpression()
//        }
//    }

    companion object {
        fun newInstance(audioSessionId: Int): PlayFragment {
            val args = Bundle()
            args.putInt(PlayFragment().ARG_AUDIO_SESSIOIN_ID, audioSessionId)

            val fragment = PlayFragment()
            fragment.arguments = args
            return fragment
        }

        var positionType = 0
    }

    @SuppressLint("UseRequireInsteadOfGet")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        // Khởi tạo Firebase Analytics
//        mFirebaseAnalytics = FirebaseAnalytics.getInstance(requireContext())
    }

    private val mainViewModel: MainViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPlayBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_music_view","View màn Home, Music","music_view")

        binding.mNameType.text = EqualizerFragment.nameTypeEffects
        sharedPreferencesUtil = SharedPreferencesUtil(requireActivity())
        setOnEvents()
        try {
            loadNativeMusicAds()
        } catch (ex: Exception){
            Log.e("11111111", ex.toString())
        }
    }

    private fun setOnEvents() {
        binding.mOff.setOnClickListener {
//            tracKingFirebaseAnalytics(
//                mFirebaseAnalytics,
//                "home_turn_on_click",
//                "Bật adjust",
//                "turn_on"
//            )
            val buttonController = ButtonController()
            buttonController.setOnOffEqualizer(false)
            binding.mOn.visibility= View.VISIBLE
            binding.mOff.visibility= View.GONE
        }
        binding.mOn.setOnClickListener {
//            tracKingFirebaseAnalytics(
//                mFirebaseAnalytics,
//                "home_turn_off_click",
//                "Tắt adjust",
//                "turn_off"
//            )
            Toast.makeText(requireContext(), "Adjusting the bands is disabled.", Toast.LENGTH_LONG)
                .show()
            val buttonController = ButtonController()
            buttonController.setOnOffEqualizer(true)
            binding.mOn.visibility= View.GONE
            binding.mOff.visibility= View.VISIBLE
        }

        binding.RLSpinner.setOnClickListener {
            if (!sharedPreferencesUtil.getBoolean("ControllerEffect")) {
                Toast.makeText(requireActivity(), "Adjusting the bands is disabled.", Toast.LENGTH_LONG)
                    .show()
            } else {
                (context as EqualizerToAppListener).onOpenActivityEffects(
                    EqualizerFragment.mListType
                )
            }
        }
//        binding.ivloading.setOnClickListener {  }
    }

    private fun init() {
        val list: ArrayList<VisualizerModel> = ArrayList()
        list.add(
            VisualizerModel(
                "0",
                ContextCompat.getDrawable(requireActivity(), R.drawable.ic_wave)
            )
        )
        list.add(
            VisualizerModel(
                "1",
                ContextCompat.getDrawable(requireActivity(), R.drawable.ic_objects)
            )
        )
        list.add(
            VisualizerModel(
                "2",
                ContextCompat.getDrawable(requireActivity(), R.drawable.ic_visual)
            )
        )
        list.add(
            VisualizerModel(
                "3",
                ContextCompat.getDrawable(requireActivity(), R.drawable.ic_around_visual)
            )
        )

        binding.mRecyclerChart.layoutManager =
            LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
        visualizerAdapter = VisualizerAdapter(
            requireActivity(),
            list,
            object : VisualizerAdapter.OnItemClickListener {
                override fun onItemClick(position: Int) {
//                    tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_music_visualizer_click","User lựa chọn visualizer mình muốn",position.toString())

                    when (list[position].type) {
                        "0" -> {
                            positionType = position
                            setUpVisualizer()
                        }

                        "1" -> {
                            positionType = position
                            setUpLineVisualizer()
                        }

                        "2" -> {
                            positionType = position
                            setUpBarVisualizer()
                        }

                        "3" -> {
                            positionType = position
                            setUpCirVisualizer()
                        }
                    }
                    visualizerAdapter?.notifyDataSetChanged()
                }
            })
        binding.mRecyclerChart.adapter = visualizerAdapter

    }

    override fun onResume() {
        super.onResume()

        try {
            binding.mNameType.text = EqualizerFragment.nameTypeEffects
            if (EqualizerFragment.bassBoost != null){
                if (EqualizerFragment.bassBoost.enabled){
                    binding.mOff.visibility = View.GONE
                    binding.mOn.visibility = View.VISIBLE
                }else{
                    binding.mOff.visibility = View.VISIBLE
                    binding.mOn.visibility = View.GONE
                }
            }
        }catch (ex :Exception){
            Log.d("nnn", "onResume Play: "+ex.toString())
        }

        if (!sharedPreferencesUtil.getBoolean("visualizer")) {
            binding.mLineBarVisualizer.release()
            binding.mCircleBarVisualizer.release()
            binding.mVisualizerPlay.release()
            binding.mRecyclerChart.visibility = View.GONE
        } else {
            binding.mRecyclerChart.visibility = View.VISIBLE
            init()
            try {
                if (sessionId != -1) {
                    when (positionType) {
                        0 -> {
                            setUpVisualizer()
                        }

                        1 -> {
                            setUpLineVisualizer()
                        }

                        2 -> {
                            setUpBarVisualizer()
                        }

                        3 -> {
                            setUpCirVisualizer()
                        }
                    }
                }
            } catch (ex: Exception) {
                //ignore
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        if (binding.mVisualizerPlay != null) binding.mVisualizerPlay.release()
//        nativeAdHelper?.unregisterAdListener(adCallback)
    }

    private fun setUpVisualizer() {
        setHideVisualizer()
        binding.mVisualizerPlay.visibility = View.VISIBLE
        // set custom color to the line.
        // define custom number of bars you want in the visualizer between (10 - 256).
        binding.mVisualizerPlay.setDensity(22F)

        // set Gap
        binding.mVisualizerPlay.setGap(2)

        // Set your media player to the visualizer.
        binding.mVisualizerPlay.setPlayer(sessionId)
    }

    private fun setUpLineVisualizer() {
        setHideVisualizer()
        binding.mLineBarVisualizer.visibility = View.VISIBLE
        // set custom color to the line.

        // define custom number of bars you want in the visualizer between (10 - 256).
        binding.mLineBarVisualizer.setDensity(60F)

        // Set your media player to the visualizer.
        binding.mLineBarVisualizer.setPlayer(sessionId)
    }

    private fun setUpCirVisualizer() {
        setHideVisualizer()
        binding.mCircleBarVisualizer.visibility = View.VISIBLE
        // Set your media player to the visualizer.
        binding.mCircleBarVisualizer.setPlayer(sessionId)
    }

    private fun setUpBarVisualizer() {
        setHideVisualizer()
        binding.mBarVisualizer.visibility = View.VISIBLE

        // set custom color to the line.
        binding.mBarVisualizer.setColor(
            ContextCompat.getColor(
                requireActivity(),
                R.color.center
            )
        )

        // Set your media player to the visualizer.
        binding.mBarVisualizer.setPlayer(sessionId)
    }

    private fun setHideVisualizer() {
        binding.mLineBarVisualizer.visibility = View.GONE
        binding.mCircleBarVisualizer.visibility = View.GONE
        binding.mVisualizerPlay.visibility = View.GONE
        binding.mBarVisualizer.visibility = View.GONE
    }

    override fun onStart() {
        super.onStart()

        val nameObserver = Observer<MediaInfo> { newName ->
            if (newName == null) return@Observer
            binding.mTxtName.text = newName.title
            binding.mTxtSinger.text = newName.description
        }
        mainViewModel.updateInformation.observe(this, nameObserver)

        val stateObserver = Observer<MainViewModel.State> { newName ->
            if (newName == null) return@Observer
            Log.d("qqq", "stateObserver: "+newName)
            if (newName == MainViewModel.State.PAUSE) {
                binding.ivPause.visibility = View.VISIBLE
                binding.ivPlay.visibility = View.GONE
            } else {
                binding.ivPause.visibility = View.GONE
                binding.ivPlay.visibility = View.VISIBLE
            }
        }
        mainViewModel.updateState.observe(this, stateObserver)

        binding.ivPlay.setOnClickListener {
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_music_play_click","User click Play","play_click")
            if (isPlayClick){
                isPlayClick = false
                (activity as MainActivity).play()
                Handler().postDelayed({
                    isPlayClick = true
                },1000)
            }
        }

        binding.ivPause.setOnClickListener {
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_music_pause_click","User click Pause","play_click")
            if (isPauseClick){
                isPauseClick = false
                (activity as MainActivity).pause()
                Handler().postDelayed({
                    isPauseClick = true
                },1200)
            }
        }

        binding.ivSkip.setOnClickListener {
            if (isSkipClick){
                isSkipClick = false
                if (activity is MainActivity) {
                    (activity as MainActivity).skipToPrevious()
                }
                Handler().postDelayed({
                    isSkipClick = true
                },1200)
            }
        }
        binding.ivNext.setOnClickListener {
            if (isNextClick){
                isNextClick = false
                if (activity is MainActivity) {
                    (activity as MainActivity).skipToNext()
                }
                Handler().postDelayed({
                    isNextClick = true
                },1000)
            }

        }
    }

    @Subscribe
    fun onMessageEvent(event: MessageEvent) {
        // Xử lý sự kiện tại đây
        val message = event.message
        binding.mNameType.text = message
    }

    @Subscribe
    fun onMessageEvent(event: PlayAdsEvent) {
        // Xử lý sự kiện tại đây
//        if (event.status){
//            if (nativeAdHelper!=null){
//                nativeAdHelper?.requestAds(NativeAdParam.Request.create())
//            }
//        }
    }

    private fun loadNativeMusicAds() {
//        if (FirebaseRemoteConfig.getInstance()
//                .getBoolean(Constants.Native_music) && AppUtils.haveNetworkConnection(activity)) {
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"Native_music_view","view ad tại màn Music","music_view")
//            nativeAdHelper = initNativeAd()
//            nativeAdHelper?.setNativeContentView(binding.nativeMusic)
//            nativeAdHelper?.setShimmerLayoutView(ShimmerFrameLayout(requireContext()))
//            nativeAdHelper?.registerAdListener(adCallback)
//            binding.nativeMusic.visibility = View.VISIBLE
//            if (nativeAdHelper?.nativeAd != null) {
//                nativeAdHelper?.requestAds(NativeAdParam.Ready(nativeAdHelper?.nativeAd!!))
//            }else{
//                nativeAdHelper?.requestAds(NativeAdParam.Request.create())
//            }
//        } else {
//
//        }
    }

//    private fun initNativeAd(): NativeAdHelper {
//        val config = NativeAdConfig(
//            BuildConfig.Native_music,
//            true,
//            FirebaseRemoteConfig.getInstance()
//                .getBoolean(Constants.allow_reload_native_music),
//            // with native additional layout native ad
//            R.layout.custom_native_admod_mediums
//        )
//        return NativeAdHelper(requireActivity(),  requireActivity(), config)
//    }

}