package com.base.filerecoveryrecyclebin.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import android.widget.Toast
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.filerecoveryrecyclebin.ads.admob.AdmobBannerUtils
import com.base.filerecoveryrecyclebin.bean.MediaBean
import com.base.filerecoveryrecyclebin.databinding.ActivityMainBinding
import com.base.filerecoveryrecyclebin.fragment.HomeFragment
import com.base.filerecoveryrecyclebin.fragment.RecoveryFragment
import com.base.filerecoveryrecyclebin.fragment.RecycleBinFragment
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.MediaStoreHelp.getImageMedia
import com.base.filerecoveryrecyclebin.help.PermissionHelp.checkStorePermission
import com.base.filerecoveryrecyclebin.service.StayNotificationService
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.BarUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.base.filerecoveryrecyclebin.utils.SimilarHelper.calculateSimilar
import com.base.filerecoveryrecyclebin.view.DialogViews.showExitDialog
import com.base.filerecoveryrecyclebin.view.PermissionDialog.showPermissionBottomSheet
import com.base.filerecoveryrecyclebin.view.RateStarPop.showRateStarPopDialog
import com.facebook.appevents.AppEventsLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import java.io.File
import java.util.Locale


class MainActivity : BaseActivity<ActivityMainBinding>() {
    private val TAG = "MainActivity"
    override val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val homeFragment by lazy {
        HomeFragment()
    }
    private val recoveryFragment by lazy {
        RecoveryFragment()
    }
    private val recycleBinFragment by lazy {
        RecycleBinFragment()
    }
    private val fragments by lazy {
        mutableListOf(homeFragment, recoveryFragment, recycleBinFragment)
    }


    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.parseColor("#F2F3F7"))
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

//        System.loadLibrary("opencv_java4")

        if (!checkStorePermission()) {
            if (dialog == null) {
                dialog = showPermissionBottomSheet(launcher) {
                    binding.flBanner.visibility = View.VISIBLE
                    AdmobBannerUtils.showCollapsibleBannerAd(this, binding.flBanner)
                }
            }
        } else {
            binding.flBanner.visibility = View.VISIBLE
            AdmobBannerUtils.showCollapsibleBannerAd(this, binding.flBanner)
        }

        binding.viewpager2.run {
            adapter = object : FragmentStateAdapter(this@MainActivity) {
                override fun getItemCount(): Int {
                    return fragments.size
                }

                override fun createFragment(position: Int): Fragment {
                    return fragments[position]
                }
            }
        }

        binding.viewpager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                setPageIndicate(position)
            }
        })

        binding.ll1.setOnClickListener {
            binding.viewpager2.currentItem = 0
            BarUtils.setStatusBarColor(this, Color.parseColor("#F2F3F7"))
        }

        binding.ll2.setOnClickListener {
            binding.viewpager2.currentItem = 1
            BarUtils.setStatusBarColor(this, Color.parseColor("#F4F5F9"))
        }
        binding.ll3.setOnClickListener {
            binding.viewpager2.currentItem = 2
            BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        }

        val fbhome = AppPreferences.getInstance().getInt("fb_home", 0)
        if (fbhome == 0) {
            val logger = AppEventsLogger.newLogger(this)
            logger.logEvent("home")
            AppPreferences.getInstance().put("fb_home", 1)
        }


    }

    private fun initStayServiceObserver() {
        startService(Intent(this, StayNotificationService::class.java).apply {
            this.action = StayNotificationService.MEDIA_OBSERVER_ACTION
        })
        startService(Intent(this, StayNotificationService::class.java).apply {
            this.action = StayNotificationService.FILE_OBSERVER_ACTION
            putExtra("isStart", true)
        })
    }

    private fun setPageIndicate(p: Int) {
        binding.ll1.isSelected = false
        binding.ll2.isSelected = false
        binding.ll3.isSelected = false
        binding.tv1.typeface = Typeface.DEFAULT
        binding.tv2.typeface = Typeface.DEFAULT
        binding.tv3.typeface = Typeface.DEFAULT
        when (p) {
            0 -> {
                binding.ll1.isSelected = true
                binding.tv1.typeface = Typeface.DEFAULT_BOLD
            }

            1 -> {
                binding.ll2.isSelected = true
                binding.tv2.typeface = Typeface.DEFAULT_BOLD
            }

            2 -> {
                binding.ll3.isSelected = true
                binding.tv3.typeface = Typeface.DEFAULT_BOLD
            }
        }
    }

    fun setPage(p: Int) {
        binding.viewpager2.currentItem = p
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showExitDialog()
        }
    }


    var photoSizeFlow: MutableSharedFlow<Pair<Long, Long>> = MutableSharedFlow()


    override fun onResume() {
        super.onResume()

        if (checkStorePermission()) {
            initStayServiceObserver()
            initPhotoSize()
        }

        lifecycleScope.launch(Dispatchers.Main) {
            delay(1000)
            showRateStarPopDialog()
        }
    }

    private fun initPhotoSize() = lifecycleScope.launch(Dispatchers.IO) {
        LogEx.logDebug(TAG, "initPhotoSize")

        val list = arrayListOf<MediaBean>()
        getImageMedia(list)

        val screenSize =
            list.filter { it.path.lowercase(Locale.ENGLISH).contains("screenshot") }.map { File(it.path) }.sumOf { it.length() }

        val similar = calculateSimilar(list).flatMap { it.value }.map { File(it.path) }.sumOf { it.length() }


        LogEx.logDebug(TAG, "screenSize=$screenSize")

        delay(1500)
        photoSizeFlow.emit(Pair(screenSize, similar))
    }

}