package com.gamedog.vididin.main

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.view.LayoutInflater
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.ama.core.architecture.appBase.AppViewsActivity
import com.ama.core.architecture.appBase.OnFragmentBackgroundListener
import com.ama.core.architecture.ext.toast
import com.ama.core.architecture.util.SpUtil
import com.ama.core.architecture.util.bindViewPager2
import com.ama.core.architecture.util.setCommonNavigator
import com.ama.core.architecture.util.setDataOrAdapter
import com.ama.core.common.util.asSafe
import com.blankj.utilcode.util.ActivityUtils
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.VidiConst.GUIDE_INDEX_GIFT
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.adapter.MainTabsAdapter
import com.gamedog.vididin.adapter.MainViewPagerAdapter
import com.gamedog.vididin.main.fragments.task.DailySignSuccessDialog
import com.gamedog.vididin.main.interfaces.OnTabStyleListener
import com.gamedog.vididin.manager.DateChangeReceiver
import com.gamedog.vididin.manager.GuideManager
import com.gamedog.vididin.manager.NotificationController
import com.gamedog.vididin.router.Router
import com.remax.base.report.DataReportManager
import com.remax.base.utils.ActivityLauncher
import com.remax.notification.builder.LANDING_NOTIFICATION_ACTION
import com.remax.notification.builder.LANDING_NOTIFICATION_CONTENT
import com.remax.notification.builder.LANDING_NOTIFICATION_FROM
import com.remax.notification.builder.LANDING_NOTIFICATION_TITLE
import com.remax.notification.check.NotificationCheckController
import com.remax.notification.config.PushContent
import com.remax.notification.controller.NotificationLandingController
import com.remax.notification.newUtil.events.AppInstallReceiver
import com.remax.notification.newUtil.events.PowerConnectionReceiver
import com.remax.notification.service.NotificationKeepAliveServiceManager
import com.viddin.videos.free.R
import dagger.hilt.android.AndroidEntryPoint
import com.gamedog.vididin.main.MainUiState as UiState
import com.gamedog.vididin.main.MainViewModel as ViewModel
import com.viddin.videos.free.databinding.ActivityMainBinding as ViewBinding


@AndroidEntryPoint
class MainActivity : AppViewsActivity<ViewBinding, UiState, ViewModel>(), OnTabStyleListener {

    private lateinit var mAppInstallReceiver: AppInstallReceiver
    private lateinit var mPowerReceiver: BroadcastReceiver
    private lateinit var activityLauncher: ActivityLauncher
    override val mViewModel: ViewModel by viewModels()
    private lateinit var navigatorAdapter: MainTabsAdapter
    private val fragmentStateAdapter by lazy { MainViewPagerAdapter(this) }
    private lateinit var mDateChangeReceiver: DateChangeReceiver



    override fun inflateViewBinding(inflater: LayoutInflater) = ViewBinding.inflate(inflater)

    override fun ViewBinding.initWindowInsets() {
        setImmerseRootView(flForImmerse)
    }


    override fun ViewBinding.initViews() {
        activityLauncher = ActivityLauncher(this@MainActivity)

        navigatorAdapter = MainTabsAdapter(
            this@MainActivity, viewPager2, fragmentStateAdapter, magicIndicator
        )
        magicIndicator.setCommonNavigator { isAdjustMode = true }
        magicIndicator.bindViewPager2(viewPager2)

        viewPager2.isUserInputEnabled = false
        viewPager2.setPageTransformer { _, _ -> }
        viewPager2.offscreenPageLimit


        if (GuideManager.instance().getCurGuideIndex() < GUIDE_INDEX_GIFT) {
            BeginnerGiftDialog(this@MainActivity).show()
        }
    }

    override fun ViewBinding.initListeners() {
        mDateChangeReceiver = DateChangeReceiver()
        val filter = IntentFilter(Intent.ACTION_DATE_CHANGED)
        registerReceiver(mDateChangeReceiver, filter)
        registerReceivers()

        onBackPressedDispatcher.addCallback(this@MainActivity) {
            if (mViewModel.canBack) {
                finish()
            } else {
                toast(R.string.close_app_hint)
                mViewModel.startCanBackTimer()
            }
        }

        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
            }
        })

        supportFragmentManager.registerFragmentLifecycleCallbacks(object :
            FragmentLifecycleCallbacks() {
            override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
                super.onFragmentResumed(fm, f)
                val isBackgroundBright =
                    f.asSafe<OnFragmentBackgroundListener>()?.isBackgroundBright
                        ?: return

                onTabIsDarkFont(isBackgroundBright)
            }
        }, false)

        registerEvents( { data->
            when (data?.mEventType) {
                VididinEvents.EVENT_AD_WATCHED_FOR_EARN_GOLD-> {
                    DailySignSuccessDialog(this@MainActivity).initData(VidiConst.WATCH_AD_REWARD_GOLD.toInt(), false).show()
                }

                VididinEvents.EVENT_JUMP_2_VIDEO-> {
                    switchTab(0)
                }
            }

        }, VididinEvents.EVENT_AD_WATCHED_FOR_EARN_GOLD, VididinEvents.EVENT_JUMP_2_VIDEO)
    }

    override fun ViewBinding.initObservers() {
        checkNotifyPermissionAndStartService()
        handleNotificationAction()
        reportStatistics(intent, true)
    }


    override fun ViewBinding.onUiStateCollect(uiState: UiState) {
        magicIndicator.setDataOrAdapter(uiState.tabs) { navigatorAdapter }
        viewPager2.setDataOrAdapter(uiState.tabs, Int.MAX_VALUE) { fragmentStateAdapter }
    }


    override fun onResume() {
        super.onResume()
        StatisticUtil.reportEvents(StatisticUtil.KEY_Home_Show)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(mDateChangeReceiver)
        unregisterReceivers()
    }

    override fun onTabIsDarkFont(isDarkFont: Boolean) {
        navigatorAdapter.setIsDarkFont(isDarkFont)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleNotificationAction()
        reportStatistics(intent, true)
    }

    fun switchTab(itemIndex: Int) {
        binding.viewPager2.setCurrentItem(itemIndex, false)
    }

    private fun handleNotificationAction() {
        if (NotificationLandingController.isFromNotification(intent)) {
            val notificationAction = intent.getIntExtra(LANDING_NOTIFICATION_ACTION, -1)
            when (notificationAction) {
                PushContent.ACTION_TYPE_GAME -> {
                    Router.Game.startActivity(this)
                }

                PushContent.ACTION_TYPE_GOLD -> {
                    switchTab(1)
                }

                PushContent.ACTION_TYPE_WITHDRAW -> {
                    Router.Withdraw.startActivity(this)
                }

                PushContent.ACTION_TYPE_BOX -> {
                    Router.Benefit.startActivity(this)
                }
            }
            NotificationLandingController.clearNotificationParameters(intent)

            sendNotificationClickStatistics(notificationAction)
        }
    }

    private fun sendNotificationClickStatistics(notificationAction: Int) {
        var pushType = 1
        if (notificationAction == PushContent.ACTION_TYPE_GAME
            || notificationAction == PushContent.ACTION_TYPE_GOLD
            || notificationAction == PushContent.ACTION_TYPE_WITHDRAW
            || notificationAction == PushContent.ACTION_TYPE_BOX ) {
            pushType = 2
        }

        StatisticUtil.reportEvents(StatisticUtil.KEY_Push_Click, mapOf(
            "Push_Position" to pushType,
            "Push_Type" to pushType
        ))

        StatisticUtil.reportEvents(StatisticUtil.KEY_Push_EnterGame, mapOf(
            "Push_Position" to pushType,
            "Push_Type" to pushType
        ))
    }

    private fun checkNotifyPermissionAndStartService() {
        NotificationController.requestNotificationPermissionAsAsync(
            context = this,
            lifecycleScope = lifecycleScope,
            activityLauncher = activityLauncher!!,
            position = "Appstart",
            onGrantedOnlyUnauthorized = { isGranted->
                if(isGranted){
                    NotificationKeepAliveServiceManager.startKeepAliveService(this)
                }
            })
    }


    private fun reportStatistics(intent: Intent, isFromNewIntent: Boolean) {
        // AppOpen
        DataReportManager.reportData(
            VidiConst.STATISTICS_APP_OPEN,
            mapOf(
                "type" to if (ActivityUtils.isActivityExistsInStack(MainActivity::class.java)) "hot_open" else "cold_open",
                "position" to if (intent.hasExtra(LANDING_NOTIFICATION_FROM)) intent.getStringExtra(
                    LANDING_NOTIFICATION_FROM).orEmpty().ifBlank { "other" } else "other"
            ))

        // Notific_Click
        if (intent.hasExtra(LANDING_NOTIFICATION_FROM)) {
            val notifyFrom = intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()

            DataReportManager.reportData(
                VidiConst.STATISTICS_NOTIFI_CLICK, mapOf(
                    "Notific_Type" to when (notifyFrom) {
                        NotificationCheckController.NotificationType.UNLOCK.string -> 1
                        NotificationCheckController.NotificationType.BACKGROUND.string -> 1
                        NotificationCheckController.NotificationType.FIXTIMEPOINT.string -> 1
                        NotificationCheckController.NotificationType.KEEPALIVE.string -> 1
                        NotificationCheckController.NotificationType.FCM.string -> 3
                        NotificationCheckController.NotificationType.RESIDENT.string -> 4
                        else -> 4
                    },
                    "Notific_Position" to when (intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()) {
                        NotificationCheckController.NotificationType.RESIDENT.string -> 2
                        else -> 1
                    },
                    "Notific_Priority" to when (intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()) {
                        NotificationCheckController.NotificationType.RESIDENT.string -> "PRIORITY_DEFAULT"
                        else -> "PRIORITY_MAX"
                    },
                    "event_id" to when (intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()) {
                        NotificationCheckController.NotificationType.RESIDENT.string -> "permanent"
                        else -> "customer_general_style"
                    },
                    "title" to intent.getStringExtra(LANDING_NOTIFICATION_TITLE).orEmpty(),
                    "text" to intent.getStringExtra(LANDING_NOTIFICATION_CONTENT).orEmpty(),
                    "from_background" to /*!ActivityUtils.isActivityExistsInStack(HomeActivity::class.java)*/isFromNewIntent
                )
            )


            DataReportManager.reportData(
                VidiConst.STATISTICS_NOTIFI_ENTER, mapOf(
                    "Notific_Type" to when (intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()) {
                        NotificationCheckController.NotificationType.UNLOCK.string -> 1
                        NotificationCheckController.NotificationType.BACKGROUND.string -> 1
                        NotificationCheckController.NotificationType.FIXTIMEPOINT.string -> 1
                        NotificationCheckController.NotificationType.KEEPALIVE.string -> 1
                        NotificationCheckController.NotificationType.FCM.string -> 3
                        NotificationCheckController.NotificationType.RESIDENT.string -> 4
                        else -> 4
                    },
                    "Notific_Position" to when (intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()) {
                        NotificationCheckController.NotificationType.RESIDENT.string -> 2
                        else -> 1
                    },
                    "Notific_Priority" to when (intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()) {
                        NotificationCheckController.NotificationType.RESIDENT.string -> "PRIORITY_DEFAULT"
                        else -> "PRIORITY_MAX"
                    },
                    "event_id" to when (intent.getStringExtra(LANDING_NOTIFICATION_FROM).orEmpty()) {
                        NotificationCheckController.NotificationType.RESIDENT.string -> "permanent"
                        else -> "customer_general_style"
                    },
                    "title" to intent.getStringExtra(LANDING_NOTIFICATION_TITLE).orEmpty(),
                    "text" to intent.getStringExtra(LANDING_NOTIFICATION_CONTENT).orEmpty(),
                )
            )
        }
    }

    private fun registerReceivers() {
        mPowerReceiver = PowerConnectionReceiver()
        val filter1 = IntentFilter().apply {
            addAction(Intent.ACTION_POWER_CONNECTED)
            addAction(Intent.ACTION_POWER_DISCONNECTED)
        }
        registerReceiver(mPowerReceiver, filter1)

        mAppInstallReceiver = AppInstallReceiver()
        val filter2 = IntentFilter().apply {
            addAction(Intent.ACTION_PACKAGE_ADDED)
            addAction(Intent.ACTION_PACKAGE_REPLACED)
            addAction(Intent.ACTION_PACKAGE_REMOVED)
            addDataScheme("package")
        }
        registerReceiver(mAppInstallReceiver, filter2)
    }


    private fun unregisterReceivers() {
        unregisterReceiver(mPowerReceiver)
        unregisterReceiver(mAppInstallReceiver)
    }


    companion object {
        internal fun startActivity(activity: Activity) {
            activity.startActivity(Intent(activity.applicationContext, MainActivity::class.java))
        }
    }


}