package importantedto.candidateedto

import android.annotation.SuppressLint
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.databinding.FlamboyantedtoBinding
import importantedto.afteredto.constitutionaledto.Jumpedto
import importantedto.afteredto.constitutionaledto.Memberedto.getImageMedia
import importantedto.afteredto.constitutionaledto.Memberedto.getVideoMedia
import importantedto.appliededto.surgeonedto.promiseedto.respectableedto.prisonedto.comfortableedto.Hopeedto
import importantedto.concreteedto.cameedto.Commentedto
import importantedto.concreteedto.cameedto.Vigorousedto
import importantedto.deserveedto.manufactureredto.viableedto.Eagleedto
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Locale

class Flawededto(val type: String) : Jumpedto<FlamboyantedtoBinding>() {

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

    override fun setView() {
        adapter = Eagleedto { pair ->
            binding.bazaaredto.text = if (pair.first) "Unselect ALL" else "Select All"
            (requireActivity() as Hopeedto).showCardImport(type,pair.second)
        }
        binding.questedto.adapter = adapter

        initData()
    }

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

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

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

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

    }


}