package rowedto.jockeyedto.sheetedto.slideedto

import android.annotation.SuppressLint
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.databinding.ArticleedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rowedto.jockeyedto.sheetedto.atticedto.harboredto.Princeedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Cunningedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Sisteredto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Affairedto.getImageMedia
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Affairedto.getVideoMedia
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Aloofedto
import rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto.Complainedto
import java.text.SimpleDateFormat
import java.util.Locale

class Branchedto(val type: String) : Aloofedto<ArticleedtoBinding>() {

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

    override fun setView() {
        adapter = Complainedto { pair ->
            binding.glassedto.text = if (pair.first) "Unselect ALL" else "Select All"
            (requireActivity() as Princeedto).showCardImport(type,pair.second)
        }
        binding.funeraledto.adapter = adapter

        initData()
    }

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

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

        val hashMap = HashMap<String, ArrayList<Cunningedto>>()
        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 {
            Sisteredto(it.key, it.value)
        }

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

    }


}