package com.base.datarecovery.fragment

import android.annotation.SuppressLint
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.activity.privacyspace.PrivacyImportActivity
import com.base.datarecovery.adapter.MediaAdapter
import com.base.datarecovery.bean.MediaBean
import com.base.datarecovery.bean.MediaTimeBean
import com.base.datarecovery.databinding.FragmentPrivacyFileImportBinding
import com.base.datarecovery.help.BaseFragment
import com.base.datarecovery.help.MediaStoreHelp.getImageMedia
import com.base.datarecovery.help.MediaStoreHelp.getVideoMedia
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.HashMap
import java.util.Locale

class PrivacyFileImportFragment(val type: String) : BaseFragment<FragmentPrivacyFileImportBinding>() {

    override val binding: FragmentPrivacyFileImportBinding by lazy {
        FragmentPrivacyFileImportBinding.inflate(layoutInflater)
    }
    private lateinit var adapter: MediaAdapter

    override fun setView() {
        adapter = MediaAdapter { pair ->
            binding.tvSelectAll.text = if (pair.first) "Unselect ALL" else "Select All"
            (requireActivity() as PrivacyImportActivity).showCardImport(type,pair.second)
        }
        binding.rv.adapter = adapter

        initData()
    }

    @SuppressLint("SetTextI18n")
    override fun setListener() {
        binding.tvSelectAll.setOnClickListener {
            val text = binding.tvSelectAll.text
            if (text == "Unselect ALL") {
                adapter.toggleAllSelect(false)
            } else {
                adapter.toggleAllSelect(true)
            }
        }
    }

    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val list = arrayListOf<MediaBean>()
        if (type == "Photos") {
            requireContext().getImageMedia(list)
        } else {
            requireContext().getVideoMedia(list)
        }

        val hashMap = HashMap<String, ArrayList<MediaBean>>()
        list.forEach {
            val time = SimpleDateFormat("yyyy-MMM-dd", Locale.getDefault()).format(it.time)
            if (hashMap[time].isNullOrEmpty()) {
                hashMap[time] = arrayListOf()
            }
            hashMap[time]?.add(it)
        }

        val beanList = hashMap.map {
            MediaTimeBean(it.key, it.value)
        }

        launch(Dispatchers.Main) {
            adapter.setData(beanList)
        }

    }


}