package com.bassbooster.soundeffects.equalizer.view

import android.Manifest
import android.annotation.SuppressLint
import android.content.*
import android.content.pm.PackageManager
import android.media.AudioManager
import android.media.session.MediaSessionManager
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import android.view.View
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView

import com.bassbooster.equalizer.R
import com.bassbooster.soundeffects.equalizer.adapter.ViewPagerAdapter
import com.bassbooster.soundeffects.equalizer.base.ViewModelFactory
import com.bassbooster.soundeffects.equalizer.data.api.ApiHelper
import com.bassbooster.soundeffects.equalizer.data.api.ApiServiceImpl
import com.bassbooster.soundeffects.equalizer.data.model.MediaInfo
import com.bassbooster.soundeffects.equalizer.database.EffectsData
import com.bassbooster.equalizer.databinding.ActivityMainBinding
import com.bassbooster.equalizer.databinding.DialogBottomSaveBinding
import com.bassbooster.soundeffects.equalizer.event.MessageEvent
import com.bassbooster.soundeffects.equalizer.event.PlayAdsEvent
import com.bassbooster.equalizer.utils.*
import com.bassbooster.soundeffects.equalizer.adapter.ChooseAppAdapter
import com.bassbooster.soundeffects.equalizer.data.model.AppMedia
import com.bassbooster.soundeffects.equalizer.utils.CustomNotificationService.Companion.createNotificationChannel
import com.bassbooster.soundeffects.equalizer.view.activity.effects.EffectsActivity
import com.bassbooster.soundeffects.equalizer.view.activity.setting.SettingActivity
import com.bassbooster.soundeffects.equalizer.view.activity.setting.language.LanguageManager
import com.bassbooster.soundeffects.equalizer.view.fragment.HomeFragment
import com.bassbooster.soundeffects.equalizer.view.fragment.PlayFragment
import com.bassbooster.soundeffects.equalizer.viewmodel.MainViewModel
import com.bassbooster.soundeffects.equalizer.viewmodel.MyViewModel
import com.bullhead.equalizer.ButtonController
import com.bullhead.equalizer.EqualizerToAppListener
import com.bullhead.equalizer.Settings.equalizerModel
import com.bassbooster.soundeffects.equalizer.tasks.FindMediaAppsTask
import com.bassbooster.soundeffects.equalizer.utils.AppUtils
import com.bassbooster.soundeffects.equalizer.utils.MediaAppDetails
import com.bassbooster.soundeffects.equalizer.utils.NotificationListener
import com.bassbooster.soundeffects.equalizer.utils.SharedPreferencesUtil
import com.bassbooster.soundeffects.equalizer.utils.Utils
import com.bassbooster.soundeffects.equalizer.tasks.FindMediaSessionAppsTask
import com.bassbooster.soundeffects.equalizer.tasks.MediaAppControllerUtils
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus


class MainActivity : AppCompatActivity(), EqualizerToAppListener {
    private lateinit var binding: ActivityMainBinding
    private lateinit var includeBinding: DialogBottomSaveBinding

    private lateinit var mainViewModel: MainViewModel
    private lateinit var sharedPreferencesUtil: SharedPreferencesUtil
    private val mediaApps = arrayListOf<MediaAppDetails>()
    private var mMediaAppDetails:MediaAppDetails? =
        null
    private var mController: MediaControllerCompat? = null
    private var mBrowser: MediaBrowserCompat? = null
    private var sessionId: Int? = null
    private var positionTab = 0
    val scope = CoroutineScope(Dispatchers.IO) // Sử dụng luồng nền
    private lateinit var viewModel: MyViewModel
    private val mMediaSessionListener: MediaSessionListener = MediaSessionListener()
    private val searchHandler = Handler(Looper.getMainLooper())
    private val listPresetName = arrayListOf<String>()
    private val languageManager = LanguageManager()
    private var statusPlayMedia = false
//    private var mFirebaseAnalytics: FirebaseAnalytics? = null
    private var adsHomeIsVisible = true

    companion object {
        val RESTART_APP_FLAG = "restart_app_flag"
        @SuppressLint("StaticFieldLeak")
//        var nativeAdHelper: NativeAdHelper? = null
        var statusFistTimeTab = false
        var statusFistTimeSelectMusic = false
    }

//    val adCallback = object : AperoAdCallback() {
//        override fun onAdClicked() {
//            super.onAdClicked()
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"Native_home_click","click ad tại màn Home","home_click")
//        }
//
//        override fun onAdImpression() {
//            super.onAdImpression()
//            if (!adsHomeIsVisible && viewPager2.currentItem != 0){
//                binding.nativeHome.visibility = View.GONE
//                adsHomeIsVisible = true
//            }
//        }
//    }

    private val mCallback: MediaControllerCompat.Callback =
        object : MediaControllerCompat.Callback() {
            override fun onPlaybackStateChanged(playbackState: PlaybackStateCompat?) {
                if (playbackState!=null){

                    onUpdate()
                    Log.d("qqq", "onPlaybackStateChanged: " + playbackState.state)
                    if (playbackState.state == 2) {
                        mainViewModel.updateState(true)
                    } else {
                        if (playbackState.state == 0 || playbackState.state == 1) {
                            mainViewModel.updateState(true)
                        } else {
                            mainViewModel.updateState(false)
                        }
                    }
                }
            }

            override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
                if (metadata!=null){
                    onUpdate()
                }
            }

            override fun onSessionDestroyed() {
                Log.d("iii", "onSessionDestroyed: ")
            }

            private fun onUpdate() {
                try {
                    val metadata = mController?.metadata
                    if (metadata != null) {
                        val title =
                            metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE) ?: ""
                        val description =
                            metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST) ?: ""
                        mainViewModel.updateInfo(title, description)
                    }
                } catch (ex: Exception) {

                }

            }
        }

    @RequiresApi(Build.VERSION_CODES.M)
    @SuppressLint("QueryPermissionsNeeded")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharedPreferencesUtil = SharedPreferencesUtil(this)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        if(sharedPreferencesUtil.getIsStatusSelectMusic("selectMusic")){
            binding.mViewSelect.visibility = View.VISIBLE
            binding.mViewNotSelect.visibility = View.GONE
        }else{
            binding.mViewSelect.visibility = View.GONE
            binding.mViewNotSelect.visibility = View.VISIBLE
        }
        // Khởi tạo Firebase Analytics
//        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this)

        AppUtils.hideNavigationBar(this)
        includeBinding = DialogBottomSaveBinding.inflate(layoutInflater)
        mMediaSessionListener.onCreate(context = this)
        setupViewModel()
        val isReStartApp = sharedPreferencesUtil.getStatusRestart(RESTART_APP_FLAG)

        if (isReStartApp) {
            sharedPreferencesUtil.saveStatusRestart(RESTART_APP_FLAG, false)
            init()
            setupUI()
        } else {
            if (checkAudioPermission()) {
                checkPermissionNotification()
            } else {
                requestAudioPermission()
            }
        }

        setOnEvent()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 28) { // Sử dụng requestCode bạn đã chọn ở bước 1
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkPermissionNotification()
            } else {
                DialogUtils.showDialog(this,
                    resources.getString(R.string.notification_content_visua),
                    listenerOK = {

                        val intent = Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", packageName, null)
                        intent.data = uri
                        startActivityForResult(intent, 28)
                    })
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 28) {
            if (checkAudioPermission()) {
                checkPermissionNotification()
            } else {
                DialogUtils.showDialog(this,
                    resources.getString(R.string.notification_content_visua),
                    listenerOK = {

                        val intent = Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", packageName, null)
                        intent.data = uri
                        startActivityForResult(intent, 28)
                    })
            }
        } else {
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"allow_access_ok_allow","User cấp quyền cho app truy cập player ngoài","allow_access")
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }


    private fun checkPermissionNotification() {
        if (checkModifyAudioPermission()) {
            if (!NotificationListener.isEnabled(this)) {
//                tracKingFirebaseAnalytics(mFirebaseAnalytics,"allow_access_view","View màn Allow Access","allow_access")
                DialogUtils.showDialogConfirmPer(this,
                    resources.getString(R.string.notification),
                    resources.getString(R.string.notification_content),
                    listenerOK = {
//                        tracKingFirebaseAnalytics(mFirebaseAnalytics,"allow_access_ok","User clicks ok -> vào màn cấp quyền","allow_access")

                        startActivityForResult(
                            Intent(
                                "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"
                            ), 100
                        )
//                                sharedPreferencesUtil.saveBoolean("NOTIFICATION_LISTENER_SETTINGS",true)
                    },
                    listenerCancel = {
                        init()
                        setupUI()
                    })
            } else {
                init()
                setupUI()
            }
        } else {
            requestModifyAudioPermission()
        }
    }

    private fun checkAudioPermission(): Boolean {
        return ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun checkModifyAudioPermission(): Boolean {
        return ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.MODIFY_AUDIO_SETTINGS
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestAudioPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.RECORD_AUDIO),
            28
        )
    }

    private fun requestModifyAudioPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.MODIFY_AUDIO_SETTINGS),
            27
        )
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    override fun onStart() {
        super.onStart()
//        mMediaSessionListener.onStart(this)
        /*val intentFilter = IntentFilter(CustomNotificationService.EXTRA_BUTTON_CLICKED)
        registerReceiver(notificationReceiver, intentFilter)*/
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        mMediaSessionListener.onStop()
        //unregisterReceiver(notificationReceiver)
        val svc = Intent(this, MainService::class.java)
        stopService(svc)


    }

    @SuppressLint("QueryPermissionsNeeded")
    private fun init() {
        val fragmentList = arrayListOf(
            HomeFragment.newInstance(sessionId ?: 0), PlayFragment.newInstance(sessionId ?: 0)
        )
        binding.viewPager2.adapter = ViewPagerAdapter(this, fragmentList)
        binding.viewPager2.isUserInputEnabled = false
        binding.viewPager2.offscreenPageLimit = 1
        changeTab(0)
        initListMedia()

        mainViewModel.mediaAppDetailsList.observe(this, Observer { mediaList ->
            Log.d("qqq", "init: " + mediaList.size)
            mediaApps.addAll(0, mediaList)
            val listDistinct = mediaApps.distinctBy { it.packageName }
            mediaApps.clear()
            mediaApps.addAll(listDistinct)

            if (mediaApps.isNotEmpty()) {
                val packageName: String = sharedPreferencesUtil.getString("appChoose")
                mMediaAppDetails = mediaApps.firstOrNull { it.packageName == packageName }
                Log.d("qqq", "packageName init: $packageName")
            }
            if (mMediaAppDetails != null) {
                Log.d("qqq", "mMediaAppDetails init: " + mMediaAppDetails?.packageName)
                setupMedia()
            }
        })


        //creat notification
        createNotificationChannel(this@MainActivity)

        /*val eq = Equalizer(0, sessionId ?: 0)

        for (i in 0 until eq.numberOfPresets) {
            Log.d("Equalizer", eq.getPresetName(i.toShort()))
            listPresetName.add(eq.getPresetName(i.toShort()))
        }
        if (listPresetName.isNotEmpty()) {
            showBasicNotification(this@MainActivity, listPresetName[0], statusOnOff, isLightOn)
        }*/

    }

    private fun setupUI() {
        val stateObserver = Observer<MainViewModel.State> { newName ->
            if (newName == null || (this.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)?.isMusicActive == false) return@Observer
            if (newName == MainViewModel.State.PAUSE) {
                statusPlayMedia = true
                binding.mPlay.setImageResource(R.drawable.ic_pause)
//                binding.viewPager2.currentItem = positionTab + 1
            } else {
                statusPlayMedia = false
                binding.mPlay.setImageResource(R.drawable.ic_play_music)
            }
        }
        mainViewModel.updateState.observe(this, stateObserver)

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

    private fun onMusicClick() {
        runOnUiThread({
            binding.viewPager2.apply {
                changeTab(1)
                this.setCurrentItem(1, true)
            }
        })
    }

    @SuppressLint("ResourceAsColor")
    fun changeTab(position: Int) {

        binding.apply {
            if (position == 0) {
                binding.mRlViewPlay.visibility = View.VISIBLE
                tab1Background.setBackgroundResource(R.color.tab_selected)
                tab2Background.setBackgroundResource(R.color.transparent_00)
            } else {
                binding.mRlViewPlay.visibility = View.GONE
                tab2Background.setBackgroundResource(R.color.tab_selected)
                tab1Background.setBackgroundResource(R.color.transparent_00)
            }
        }
    }


    private fun setupViewModel() {
        mainViewModel = ViewModelProviders.of(
            this, ViewModelFactory(ApiHelper(ApiServiceImpl()))
        ).get(MainViewModel::class.java)

        viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun setOnEvent() {
        binding.cardTab1.setOnClickListener {
            runOnUiThread {
                binding.viewPager2.apply {
                    if (currentItem != 0) {
                        changeTab(0)
                        this.setCurrentItem(0, true)
                    }
                }
            }
        }

        binding.cardTab2.setOnClickListener {
            if (binding.viewPager2.currentItem == 1) return@setOnClickListener
            if (statusFistTimeTab){
                EventBus.getDefault().post(PlayAdsEvent(true))
            }else{
                statusFistTimeTab = true
            }
            onMusicClick()
        }

        binding.imgSetting.setOnClickListener {
            val intent = Intent(this@MainActivity, SettingActivity::class.java)
            startActivity(intent)
        }

        binding.tvChooseMedia.setOnClickListener {
            showBottomSheetDialog()
        }

        binding.mPlay.setOnClickListener {
            if (mainViewModel.updateState.value == MainViewModel.State.PLAY) {
                play()
            } else {
                pause()
            }
            onMusicClick()
            binding.mRlViewPlay.visibility = View.GONE
        }

        binding.mNext.setOnClickListener {
            skipToNext()
            onMusicClick()
            binding.mRlViewPlay.visibility = View.GONE
        }

        binding.mPrevious.setOnClickListener {
            skipToPrevious()
            onMusicClick()
            binding.mRlViewPlay.visibility = View.GONE
        }

        binding.includeDialog.mRlDialog.setOnClickListener {
            binding.includeDialog.mEdtEffects.setText("")
            binding.includeDialog.mRlDialog.visibility = View.GONE
            Utils.hideKeyboard(binding.includeDialog.mRlDialog, this@MainActivity)
        }
        binding.includeDialog.mViewType.setOnClickListener {}

        binding.includeDialog.icDeleteDialog.setOnClickListener {
            binding.includeDialog.mEdtEffects.setText("")
            binding.includeDialog.mRlDialog.visibility = View.GONE
            Utils.hideKeyboard(binding.includeDialog.mRlDialog, this@MainActivity)
        }

        binding.includeDialog.mLlSave.setOnClickListener {
            if (binding.includeDialog.mEdtEffects.text.toString().trim().isNotEmpty()) {
                val newEffects = EffectsData()
                newEffects.name = binding.includeDialog.mEdtEffects.text.toString().trim()
                newEffects.seekbar0 = equalizerModel.seekbarpos[0]
                newEffects.seekbar1 = equalizerModel.seekbarpos[1]
                newEffects.seekbar2 = equalizerModel.seekbarpos[2]
                newEffects.seekbar3 = equalizerModel.seekbarpos[3]
                newEffects.seekbar4 = equalizerModel.seekbarpos[4]
                newEffects.bassStrength = equalizerModel.bassStrength
                newEffects.reverbPreset = equalizerModel.reverbPreset
                scope.launch {
                    viewModel.insertData(newEffects)
                }

//                Toast.makeText(this, resources.getString(R.string.save_success), Toast.LENGTH_LONG)
//                    .show()

                val buttonController = ButtonController()
                buttonController.onUpdateNameTypeEffects(
                    binding.includeDialog.mEdtEffects.text.toString().trim()
                )
                EventBus.getDefault()
                    .post(MessageEvent(binding.includeDialog.mEdtEffects.text.toString().trim()))
                binding.includeDialog.mEdtEffects.setText("")
                binding.includeDialog.mRlDialog.visibility = View.GONE
                Utils.hideKeyboard(binding.includeDialog.mEdtEffects, this)
                //set update name effects to save

//                DialogUtils.showDialogSaveSuccess(context = this@MainActivity,"Saving",   listenerOK = {
//                    Toast.makeText(this, resources.getString(R.string.save_success), Toast.LENGTH_LONG)
//                    .show()
//                },mFirebaseAnalytics, activity = this@MainActivity)

            } else {
                Toast.makeText(
                    this, resources.getString(R.string.not_name_effects), Toast.LENGTH_LONG
                ).show()
            }
        }

        binding.includeDialog.mEdtEffects.addTextChangedListener {
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_equalizer_save_enter_name_click","Nhập tên","enter_name")
        }

        binding.mViewNotSelect.setOnClickListener {
            showBottomSheetDialog()
        }

        binding.mImgSelectMusic.setOnClickListener {
            showBottomSheetDialog()
        }
    }

    private fun setupMedia() {
        // Should now have a viable details.. connect to browser and service as needed.
        try {
            if (mMediaAppDetails!!.componentName != null) {
                mBrowser = MediaBrowserCompat(
                    this,
                    mMediaAppDetails!!.componentName,
                    object : MediaBrowserCompat.ConnectionCallback() {
                        override fun onConnected() {
                            setupMediaController()
                            Log.d("qqq", "MediaBrowserdCompat onConnected: success")
                        }

                        override fun onConnectionSuspended() {
                        }

                        override fun onConnectionFailed() {
                            Log.d("qqq", "MediaBrowserCompat onConnected: failed")
                        }
                    },
                    null
                )
//                scope.launch {
                mBrowser?.connect()
//                }
            } else if (mMediaAppDetails!!.sessionToken != null) {
                setupMediaController()
            } else {
                Log.d("qqq", "else: failed")
            }
        } catch (ex: Exception) {
            Log.d("qqq", "setupMedia: " + ex.message.toString())

        }
    }

    private fun setupMediaController() {
        try {
            var token = mMediaAppDetails!!.sessionToken
            if (token == null) {
                token = mBrowser!!.sessionToken
            }
            mController = MediaControllerCompat(this, token)

//            if (sharedPreferencesUtil.getString("appChoose") != "com.google.android.apps.youtube.music") {
                mController?.registerCallback(mCallback)
//            }

            // Force update on connect.
            mCallback.onPlaybackStateChanged(mController?.playbackState)

            try {
                if (mController?.metadata != null) {
                    mController?.metadata?.apply {
                        mCallback.onMetadataChanged(mController?.metadata)
                    }
                }
            } catch (ex: Exception) {

            }
        } catch (remoteException: RemoteException) {
            Log.e(
                "qqq", "Failed to create MediaController from session token", remoteException
            )
        }
    }

    private fun showBottomSheetDialog() {
        val bottomSheetDialog = BottomSheetDialog(this)
        bottomSheetDialog.setContentView(R.layout.bottom_sheet_dialog_layout)
        val rvList = bottomSheetDialog.findViewById<RecyclerView>(R.id.rvList)
        val rlSelect = bottomSheetDialog.findViewById<RelativeLayout>(R.id.rlSelect)
        val appChoose: String = sharedPreferencesUtil.getString("appChoose")
        val listApp = arrayListOf<AppMedia>()
        val listAppNotAccess = arrayListOf(
            "com.google.android.googlequicksearchbox",
            "com.google.android.youtube",
            "com.samsung.android.bixby.service",
            "flipboard.boxer.app",
            "com.ss.android.ugc.trill",
            "org.telegram.messenger"
        )

        for (item in mediaApps) {
            if (!listAppNotAccess.contains(item.packageName) && !item.packageName.contains("bluetooth")) {
                try{
                    listApp.add(
                        AppMedia(
                            name = item.appName,
                            avatar = item.icon,
                            item.packageName,
                            check = item.packageName == appChoose
                        )
                    )
                }catch (ex: Exception){
                    //Toast.makeText(this, ex.message, 10).show()
                }

            }
        }
        var packageName = sharedPreferencesUtil.getString("appChoose")
        rvList?.adapter = ChooseAppAdapter(apps = listApp, onItemClicked = {
            packageName = it
        })
        rlSelect?.setOnClickListener {
            sharedPreferencesUtil.saveString("appChoose", packageName)
            Log.d("111111", "user select : " + packageName)
            mMediaAppDetails = mediaApps.firstOrNull { it.packageName == packageName }
            if (mMediaAppDetails != null) {
                setupMedia()
                openMediaApp(mMediaAppDetails!!.packageName, this)
            }
            bottomSheetDialog.dismiss()
        }
        bottomSheetDialog.show()
    }

    fun play() {
        checkPlayNextMedia(1)
    }

    fun pause() {
        checkPlayNextMedia(2)
    }

    fun skipToNext() {
        checkPlayNextMedia(3)
    }

    fun skipToPrevious() {
        checkPlayNextMedia(4)
    }

    private fun openMediaApp(packageName: String, context: Context) {
        val packageManager: PackageManager = packageManager
        runOnUiThread {
            try {
                sharedPreferencesUtil.saveIsStatusSelectMusic("selectMusic",true)
                binding.mViewSelect.visibility = View.VISIBLE
                binding.mViewNotSelect.visibility = View.GONE
                val intent = Intent()
                intent.setComponent(ComponentName(packageName, AppUtils.getAppInfo(packageName, resources).startActivityName))
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }
            catch (e: ActivityNotFoundException){
                binding.mViewSelect.visibility = View.GONE
                binding.mViewNotSelect.visibility = View.VISIBLE
                sharedPreferencesUtil.saveIsStatusSelectMusic("selectMusic",false)
                DialogUtils.showDialog(context, resources.getString(R.string.not_install_app), listenerOK = {})
            }

        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onResume() {
        super.onResume()
        AppUtils.hideNavigationBar(this)

        Log.d("qqq", "onResume: " + "call")
        mMediaSessionListener.onStart(this)

//        val swPlayControl = sharedPreferencesUtil.getBoolean("swPlayControl")
//        if (swPlayControl.not()) {
//            binding.mViewSigger.isVisible = true
//            binding.tvChooseMedia.isVisible = false
//        } else {
//            binding.mViewSigger.isVisible = false
//            binding.tvChooseMedia.isVisible = true
//        }
    }

    override fun onPause() {
        super.onPause()
        Utils.hideAdsResume()
    }

    @SuppressLint("NewApi")
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            AppUtils.hideNavigationBar(this)
        }
    }

    override fun onOpenActivitySave() {
        binding.includeDialog.mRlDialog.visibility = View.VISIBLE
    }

    override fun onOpenActivityEffects(list: java.util.ArrayList<String>?) {
//        tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_list_genres_click","User click vào màn List Effect","list_genres")
        val intent = Intent(this, EffectsActivity::class.java)
        intent.putStringArrayListExtra("listType", list)
        startActivity(intent)
    }

    var statusMediaAppEntriesRun: Boolean = true

    private inner class MediaSessionListener {
        private val mSessionAppsUpdated: FindMediaAppsTask.AppListUpdatedCallback =
            object : FindMediaAppsTask.AppListUpdatedCallback {
                override fun onAppListUpdated(mediaAppEntries: List<MediaAppDetails>) {
                    if (mediaAppEntries.isEmpty()) {
                        Log.d("qqq", "mediaAppEntries : null return")
                        // Hiển thị thông báo lỗi nếu không tìm thấy ứng dụng nào.
                        return
                    }
                    mediaAppEntries.forEach {
                        Log.d("qqq", "mediaAppEntries : not null" + it.packageName)
                    }

                    if (statusMediaAppEntriesRun) {
                        statusMediaAppEntriesRun = false
                        Log.d("qqq", "setMediaAppDetailsList : not null")
                        mainViewModel.setMediaAppDetailsList(mediaAppEntries)
                        searchHandler.postDelayed({
                            statusMediaAppEntriesRun = true
                        }, 500)
                    }
                }
            }
        private val mSessionsChangedListener =
            MediaSessionManager.OnActiveSessionsChangedListener { list ->
                try {
                    list?.let {
                        MediaAppControllerUtils.getMediaAppsFromControllers(
                            it, packageManager, resources
                        )
                    }?.let {
                        mSessionAppsUpdated.onAppListUpdated(it)
                    }
                } catch (ex: Exception) {
                    Log.d("qqq", "onCreate: " + ex.message.toString())
                }
            }
        private var mMediaSessionManager: MediaSessionManager? = null

        fun onCreate(context: Context) {
            if (!NotificationListener.isEnabled(context)) {
                Log.d("qqq", "onCreate: " + "onCreate")
                return
            }
            mMediaSessionManager =
                getSystemService(Context.MEDIA_SESSION_SERVICE) as? MediaSessionManager
        }

        fun onStart(context: Context) {
            if (!NotificationListener.isEnabled(context)) {
                return
            }
            if (mMediaSessionManager == null) {
                Log.d("qqq", "mMediaSessionManager: null ")
                return
            }
            try {
                val listenerComponent = ComponentName(
                    context,
                    NotificationListener::class.java
                )
                mMediaSessionManager?.addOnActiveSessionsChangedListener(
                    mSessionsChangedListener, listenerComponent
                )
                FindMediaSessionAppsTask(
                    mMediaSessionManager!!,
                    listenerComponent,
                    packageManager,
                    resources,
                    mSessionAppsUpdated
                ).execute()
            } catch (ex: Exception) {
                Log.d("qqq", "onStart: " + ex.message.toString())
            }
        }

        fun onStop() {
            if (mMediaSessionManager == null) {
                return
            }
            mMediaSessionManager?.removeOnActiveSessionsChangedListener(mSessionsChangedListener)
        }
    }

    /*private val notificationReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        @RequiresApi(Build.VERSION_CODES.N)
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == CustomNotificationService.EXTRA_BUTTON_CLICKED) {
                Log.d(
                    "mmm", "intent EXTRA_BUTTON ${
                        intent.getIntExtra(
                            CustomNotificationService.EXTRA_BUTTON, -1
                        )
                    }"
                )
                val id = intent.getIntExtra(CustomNotificationService.EXTRA_BUTTON, -1)
                val text = intent.getStringExtra(CustomNotificationService.EXTRA_BUTTON_TEXT)
                when (id) {
                    R.id.icLeft -> {
                        if (context != null) {
                            val index = listPresetName.indexOf(text)
                            if (index > 1) {
                                showBasicNotification(
                                    context,
                                    listPresetName[index - 1],
                                    statusOnOff,
                                    isLightOn
                                )
                                val buttonController = ButtonController()
                                buttonController.onUpdateType(index - 1, listPresetName[index - 1])

                                this@MainActivity.findViewById<Button>(R.id.mSave)?.apply {
                                    performClick()
                                }
                            } else {
                                showBasicNotification(
                                    context,
                                    listPresetName[listPresetName.lastIndex],
                                    statusOnOff,
                                    isLightOn
                                )
                                val buttonController = ButtonController()
                                buttonController.onUpdateType(
                                    listPresetName.lastIndex,
                                    listPresetName[listPresetName.lastIndex]
                                )

                                this@MainActivity.findViewById<Button>(R.id.mSave)?.apply {
                                    performClick()
                                }
                            }
                        }
                    }

                    R.id.icRight -> {
                        if (context != null) {
                            val index = listPresetName.indexOf(text)
                            if (index < listPresetName.lastIndex) {
                                showBasicNotification(
                                    context,
                                    listPresetName[index + 1],
                                    statusOnOff,
                                    isLightOn
                                )
                                val buttonController = ButtonController()
                                buttonController.onUpdateType(index + 1, listPresetName[index + 1])

                                this@MainActivity.findViewById<Button>(R.id.mSave)?.apply {
                                    performClick()
                                }
                            } else {
                                showBasicNotification(
                                    context,
                                    listPresetName[0],
                                    statusOnOff,
                                    isLightOn
                                )
                                val buttonController = ButtonController()
                                buttonController.onUpdateType(0, listPresetName[0])

                                this@MainActivity.findViewById<Button>(R.id.mSave)?.apply {
                                    performClick()
                                }
                            }
                        }
                    }

                    R.id.icLightOff -> {
                        if (context != null) {
                            isLightOn = Settings.canDrawOverlays(this@MainActivity)
                            showBasicNotification(context, "", statusOnOff, isLightOn)
                            if (sharedPreferencesUtil.getStatusWidgetEdge("isCheckPermissionwidget")) {
                                launchMainService(true)
                            } else {
                                launchMainService(false)
                            }
                        }
                    }

                    R.id.icLight -> {
                        if (context != null) {
                            isLightOn = false
                            showBasicNotification(context, "", statusOnOff, isLightOn)
                            if (sharedPreferencesUtil.getStatusWidgetEdge("isCheckPermissionwidget")) {
                                launchMainService(false)
                            } else {
                                launchMainService(false)
                            }
                        }
                    }

                    R.id.mOff -> {
                        if (context != null) {
                            statusOnOff = false
                            Log.d("qqq", "onReceive: " + EqualizerFragment.bassBoost.properties)
                            showBasicNotification(context, "", statusOnOff, isLightOn)
                            val buttonController = ButtonController()
                            buttonController.setOnOffEqualizer(false)
                        }
                    }

                    R.id.mOn -> {
                        if (context != null) {
                            statusOnOff = true
                            Log.d("qqq", "onReceive: " + EqualizerFragment.bassBoost.properties)
                            showBasicNotification(context, "", statusOnOff, isLightOn)

                            val buttonController = ButtonController()
                            buttonController.setOnOffEqualizer(true)
//                            this@MainActivity.findViewById<Button>(R.id.mSave)?.apply {
//                                performClick()
//                            }
                        }
                    }
                }
            }
        }
    }*/

    @RequiresApi(Build.VERSION_CODES.M)
    private fun launchMainService(isCheck: Boolean = true) {
        if (Settings.canDrawOverlays(this)) {
            val svc = Intent(this, MainService::class.java)
            stopService(svc)
            if (isCheck) {
                startService(svc)
            }
        }
//        finish()
    }

//    private fun loadNativeAds() {
//        if (FirebaseRemoteConfig.getInstance()
//                .getBoolean(Constants.Native_home) && AppUtils.haveNetworkConnection(this)) {
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"Native_home_view","view ad tại màn Home","home_view")
//            nativeAdHelper = initNativeAd()
//            nativeAdHelper?.setNativeContentView(binding.nativeHome)
//            nativeAdHelper?.registerAdListener(adCallback)
//            val shimmerFrameLayout =
//                findViewById<ShimmerFrameLayout>(R.id.shimmer_container_native)
//            nativeAdHelper?.setShimmerLayoutView(shimmerFrameLayout)
//            binding.nativeHome.visibility = View.VISIBLE
//
//            if (nativeAdHelper?.nativeAd != null) {
//                nativeAdHelper?.requestAds(NativeAdParam.Ready(nativeAdHelper?.nativeAd!!))
//            }else{
//                nativeAdHelper?.requestAds(NativeAdParam.Request.create())
//            }
//        } else {
//            binding.nativeHome.visibility = View.GONE
//        }
//    }

    override fun onBackPressed() {
        finishAffinity()
    }

    private fun checkPlayNextMedia(status: Int) {
        // 1. play 2. pause 3. skip 4. Previous
        if (mController != null && (mController?.isSessionReady == true)) {
            Log.d("qqq", "checkPlayNextMedia: "+mController?.playbackState?.state)
            Log.d("qqq", "checkPlayNextMedia: "+mController?.playbackState?.playbackState)
            if (sharedPreferencesUtil.getString("appChoose") != "ht.nct") {
                if ((mController?.playbackState?.state == PlaybackStateCompat.STATE_NONE ||
                    mController?.playbackState?.state == PlaybackStateCompat.STATE_STOPPED) && (mController?.metadata === null)) {
                    DialogUtils.showDialog(this, resources.getString(R.string.not_control), listenerOK = {})
                } else {
                    when (status) {
                        1 -> mController?.transportControls?.play()
                        2 -> mController?.transportControls?.pause()
                        3 -> mController?.transportControls?.skipToNext()
                        4 -> mController?.transportControls?.skipToPrevious()
                    }
                }
            } else {
                if (mController?.playbackState?.state == PlaybackStateCompat.STATE_STOPPED) {
                    DialogUtils.showDialog(this, resources.getString(R.string.not_control), listenerOK = {})
                }else{
                    when (status) {
                        1 -> mController?.transportControls?.play()
                        2 -> mController?.transportControls?.pause()
                        3 -> mController?.transportControls?.skipToNext()
                        4 -> mController?.transportControls?.skipToPrevious()
                    }
                }
            }
        } else {
            DialogUtils.showDialog(this, resources.getString(R.string.not_control), listenerOK = {})
        }
    }

    private fun initListMedia(){
        mediaApps.add(MediaAppDetails("com.gaana", null, resources));
        mediaApps.add(MediaAppDetails("com.spotify.music", null, resources));
        mediaApps.add(MediaAppDetails("com.soundcloud.android", null, resources));
        mediaApps.add(MediaAppDetails("com.google.android.apps.youtube.music", null, resources));

        if (!NotificationListener.isEnabled(this@MainActivity)) {
            if (mediaApps.isNotEmpty()) {
                val packageName: String = sharedPreferencesUtil.getString("appChoose")
                mMediaAppDetails = mediaApps.firstOrNull { it.packageName == packageName }
                Log.d("qqq", "packageName init: $packageName")
            }
            if (mMediaAppDetails != null) {
                Log.d("qqq", "mMediaAppDetails init: " + mMediaAppDetails?.packageName)
                setupMedia()
            }
        }
    }

//    private fun initNativeAd(): NativeAdHelper {
//        val config = NativeAdConfig(
//            BuildConfig.Native_home,
//            true,
//            FirebaseRemoteConfig.getInstance()
//                .getBoolean(Constants.allow_reload_native_home),
//            // with native additional layout native ad
//            R.layout.layout_loading_navite_small
//        )
//        return NativeAdHelper(this,  this, config)
//    }
}
