package com.base.datarecovery.activity.privacyspace

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.datarecovery.bean.ConstObject.rememberOption
import com.base.datarecovery.bean.ConstObject.rememberRemove
import com.base.datarecovery.bean.MediaBean
import com.base.datarecovery.databinding.ActivityPrivacyImportBinding
import com.base.datarecovery.fragment.PrivacyFileImportFragment
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.KotlinExt.toFormatSize
import com.base.datarecovery.help.MediaStoreHelp.updateMediaStore
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.LogEx
import com.base.datarecovery.view.DialogViews.showRemoveOriginalTip
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class PrivacyImportActivity : BaseActivity<ActivityPrivacyImportBinding>() {

    private val TAG = "PrivacyImportActivity"

    private val photosImportFragment: PrivacyFileImportFragment by lazy {
        PrivacyFileImportFragment("Photos")
    }
    private val videosImportFragment: PrivacyFileImportFragment by lazy {
        PrivacyFileImportFragment("Videos")
    }

    private val fragments by lazy {
        mutableListOf(photosImportFragment, videosImportFragment)
    }


    override val binding: ActivityPrivacyImportBinding by lazy {
        ActivityPrivacyImportBinding.inflate(layoutInflater)
    }


    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)

        binding.viewpager2.run {
            adapter = object : FragmentStateAdapter(this@PrivacyImportActivity) {
                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) {
                if (position == 0) {
                    binding.llPhotos.isSelected = true
                    binding.llVideos.isSelected = false
                } else {
                    binding.llVideos.isSelected = true
                    binding.llPhotos.isSelected = false
                }
            }
        })
    }

    override fun initListener() {
        super.initListener()

        binding.llPhotos.setOnClickListener {
            binding.viewpager2.currentItem = 0
        }
        binding.llVideos.setOnClickListener {
            binding.viewpager2.currentItem = 1
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
        }
    }

    private val photosPath = arrayListOf<MediaBean>()
    private val videosPath = arrayListOf<MediaBean>()

    @SuppressLint("SetTextI18n")
    fun showCardImport(type: String, list: List<MediaBean>) {
        if (type == "Photos") {
            photosPath.clear()
            photosPath.addAll(list)
        } else {
            videosPath.clear()
            videosPath.addAll(list)
        }
        val allSelect = arrayListOf<MediaBean>()
        allSelect.addAll(photosPath)
        allSelect.addAll(videosPath)
        if (allSelect.isNotEmpty()) {
            binding.cardImport.isVisible = true
            binding.tvSelectNumber.text = "${allSelect.size} Selected"
            binding.tvSize.text = allSelect.sumOf { File(it.path).length() }.toFormatSize()
            binding.tvImport.setOnClickListener {
                if (!rememberOption) {
                    showRemoveOriginalTip { isRememberOption, isRemove ->
                        rememberOption = isRememberOption
                        rememberRemove = isRemove
                        copyMediaToPrivacySpace(allSelect)
                    }
                } else {
                    copyMediaToPrivacySpace(allSelect)
                }
            }
        } else {
            binding.tvImport.setOnClickListener {}
            binding.cardImport.isVisible = false
        }
    }

    private fun copyMediaToPrivacySpace(allSelect: ArrayList<MediaBean>) {
        binding.flProgress.setOnClickListener { }
        binding.flProgress.visibility = View.VISIBLE
        lifecycleScope.launch(Dispatchers.IO) {
            allSelect.forEach {
                LogEx.logDebug(TAG, it.mimeType)
                val dir = filesDir
                val file = File(it.path)

                runCatching {
                    if (it.mimeType.contains("image")) {
                        val imageDir = File(dir, "photos")
                        file.copyTo(File(imageDir, file.name), true)
                    } else {
                        val videoDir = File(dir, "videos")
                        file.copyTo(File(videoDir, file.name), true)
                    }
                    if (rememberRemove) {
                        file.delete()
                    }
                }
            }
            updateMediaStore()

            launch(Dispatchers.Main) {
                binding.flProgress.visibility = View.GONE
                setResult(0, Intent().apply { putExtra("Result", "Success") })
                finish()
            }
        }
    }


}