package com.base.browserwhite.ui.activity.mediabrowser

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.provider.Settings
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.LinearLayoutManager
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.databinding.ActivityMediaBrowserBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.adapter.MediaAdapter
import com.base.browserwhite.ui.fragment.FileFragment
import com.base.browserwhite.ui.views.DialogViews.showGerPermission
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.IntentEx.installAokAction
import com.base.browserwhite.utils.IntentEx.viewAudioAction
import com.base.browserwhite.utils.IntentEx.viewDocumentAction
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.MediaStoreUtils.getMediaAudio
import com.base.browserwhite.utils.MediaStoreUtils.getMediaFile
import com.base.browserwhite.utils.MediaStoreUtils.getMediaPhoto
import com.base.browserwhite.utils.MediaStoreUtils.getMediaVideo
import com.base.browserwhite.utils.PermissionHelp.checkStorePermission
import com.base.browserwhite.utils.PermissionHelp.requestStorePermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class MediaBrowserActivity : BaseActivity<ActivityMediaBrowserBinding>() {

    override val binding: ActivityMediaBrowserBinding by lazy {
        ActivityMediaBrowserBinding.inflate(layoutInflater)
    }
    private val TAG = "MediaBrowserActivity"

    private lateinit var adapter: MediaAdapter
    private var tittle: String = ""
    override fun initView() {

        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        tittle = intent.extras?.getString("tittle") ?: ""

        binding.tvTitle.text = tittle

        when (tittle) {
            "Picture", "Video" -> {
                adapter = MediaAdapter(1, clickAction = { bean ->
                    if (tittle == "Picture") {
                        startActivity(Intent(this, MediaImageDetailActivity::class.java).apply {
                            putExtra("uri", bean.uri.toString())
                            putExtra("path", bean.path)
                            putExtra("mimeType", bean.mimeType)
                        })
                    } else {
                        LogEx.logDebug(TAG, "uri=${bean.uri}")
                        startActivity(Intent(this, MediaVideoDetailActivity::class.java).apply {
                            putExtra("uri", bean.uri.toString())
                            putExtra("path", bean.path)
                            putExtra("mimeType", bean.mimeType)
                        })
                    }
                })
                binding.rv.layoutManager = GridLayoutManager(this, 4).apply {
                    spanSizeLookup = object : SpanSizeLookup() {
                        override fun getSpanSize(position: Int): Int {
                            // 根据item的类型或数据来决定占据的列数
                            return 1
                        }
                    }
                }
            }

            "Document", "APK", "Music", "Zip" -> {
                adapter = MediaAdapter(2,
                    clickAction = { bean ->
                        if (tittle == "Document") {
                            this.viewDocumentAction(bean.uri, bean.mimeType)
                        }
                        if (tittle == "APK") {
                            LogEx.logDebug(TAG, "APK ${bean.uri}")
                            try {
                                this.installAokAction(bean.uri)
                            } catch (e: Exception) {
                                LogEx.logDebug(TAG, "APK $e")
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                                    launcher.launch(intent) {
                                        runCatching {
                                            this.installAokAction(bean.uri)
                                        }
                                    }
                                }
                            }
                        }
                        if (tittle == "Zip") {

                        }
                        if (tittle == "Music") {
                            this.viewAudioAction(bean.uri, bean.mimeType)
                        }
                    },
                    moreAction = { view, bean ->
                        FileFragment.moreAction(this, view, bean, adapter)
                    })
                binding.rv.layoutManager = LinearLayoutManager(this)
            }
        }

        binding.rv.adapter = adapter

        if (!checkStorePermission()) {
            showGerPermission(
                desc = "This feature requires access to your storage to scan your files and clean up junk files and unused APK files. We will not transmit your data to any third-party service. Please grant permission so that we can provide you with better service.",
            ) {
                requestStorePermission(launcher) {
                    if (!it) finishToMain()
                }
            }
        }

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    override fun onResume() {
        super.onResume()
        if (checkStorePermission()) {
            initData()
        }
    }

    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val mediaList = when (tittle) {
            "Picture" -> getMediaPhoto()
            "Video" -> getMediaVideo()
            "Document" -> getMediaFile(
                arrayOf(
                    ConstObject.MIME_TYPE_PDF,
                    ConstObject.MIME_TYPE_DOC,
                    ConstObject.MIME_TYPE_DOCX,
                    ConstObject.MIME_TYPE_XLS,
                    ConstObject.MIME_TYPE_XLSX,
                    ConstObject.MIME_TYPE_PPT,
                    ConstObject.MIME_TYPE_PPTX,
                )
            )

            "APK" -> getMediaFile(
                arrayOf(
                    ConstObject.MIME_TYPE_APK
                )
            )

            "Music" -> getMediaAudio()
            "Zip" -> getMediaFile(
                arrayOf(
                    ConstObject.MIME_TYPE_ZIP
                )
            )

            else -> arrayListOf()
        }

        launch(Dispatchers.Main) {
            adapter.setData(mediaList)
            binding.llEmpty.isVisible = mediaList.isEmpty()
        }
    }

}