package rallyedto.remarkedto.cooperationedto.agricultureedto

import android.annotation.SuppressLint
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.databinding.CardedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rallyedto.battleedto.acresedto.Affinityedto.getImageMedia
import rallyedto.battleedto.acresedto.Affinityedto.getVideoMedia
import rallyedto.battleedto.acresedto.Dolledto
import rallyedto.dumpedto.editionedto.Inspirationedto
import rallyedto.finishedto.exampleedto.Speededto
import rallyedto.policeedto.huntedto.Cookedto
import rallyedto.policeedto.huntedto.Outletedto
import java.text.SimpleDateFormat
import java.util.Locale

class Formaledto(val type: String) : Dolledto<CardedtoBinding>() {

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

    override fun setView() {
        adapter = Inspirationedto { pair ->
            binding.brownedto.text = if (pair.first) "Unselect ALL" else "Select All"
            (requireActivity() as Speededto).showCardImport(type,pair.second)
        }
        binding.autonomyedto.adapter = adapter

        initData()
    }

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

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

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

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

    }


}