package com.base.scanqrclear.luma

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.base.scanqrclear.R
import com.base.scanqrclear.databinding.ActivityWhatsappCleanBinding
import com.base.scanqrclear.luma.MineTypeHelps.TYPE_AUDIO
import com.base.scanqrclear.luma.MineTypeHelps.TYPE_IMAGE
import com.base.scanqrclear.luma.MineTypeHelps.TYPE_VIDEO
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Locale

class WhatsappCleanActivity : BaseActivity2() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, WhatsappCleanActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val binding by lazy {
        ActivityWhatsappCleanBinding.inflate(layoutInflater)
    }

    private lateinit var videoAdapter: WhatsappCleanAdapter
    private lateinit var imageAdapter: WhatsappCleanAdapter

    private var videoList = listOf<FileBean>()
    private var imageList = listOf<FileBean>()
    private var audioList = listOf<FileBean>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
        showAnimationAd(LottieType.WHATSAPP)
        onBackPressedDispatcher.addCallback {
            handleBackPressed(this@WhatsappCleanActivity)
        }
    }

    private fun initView() {
        videoAdapter = WhatsappCleanAdapter(TYPE_VIDEO)
        binding.rvVideo.adapter = videoAdapter
        binding.rvVideo.layoutManager = GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        imageAdapter = WhatsappCleanAdapter(TYPE_IMAGE)
        binding.rvImage.adapter = imageAdapter
        binding.rvImage.layoutManager = GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)

        binding.viewVideo.setOnClickListener {
            toDetail(videoList, videoAdapter.type, getString(R.string.video_messages))
        }
        binding.viewImage.setOnClickListener {
            toDetail(imageList, imageAdapter.type, getString(R.string.image_messages))
        }

        binding.flBack.setOnClickListener { backPressed() }
        binding.clVideoMessage.setOnClickListener { toDetail(videoList, videoAdapter.type, getString(R.string.video_messages)) }
        binding.clImageMessage.setOnClickListener { toDetail(imageList, imageAdapter.type, getString(R.string.image_messages)) }
        binding.llAudioMessage.setOnClickListener { toDetail(audioList, TYPE_AUDIO, getString(R.string.audio_messages)) }
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val filesDeferred = async { FileHelps.findWhatsappFiles() }
            val files = filesDeferred.await()
            videoList = files.filter { file ->
                MineTypeHelps.videos.any { suffix -> file.name.lowercase(Locale.ROOT).endsWith(suffix) }
            }
            imageList = files.filter { file ->
                MineTypeHelps.images.any { suffix -> file.name.lowercase(Locale.ROOT).endsWith(suffix) }
            }
            audioList = files.filter { file ->

                MineTypeHelps.audios.any { suffix -> file.name.lowercase(Locale.ROOT).endsWith(suffix) }
            }
            val videoSize = videoList.sumOf { it.length }
            val imageSize = imageList.sumOf { it.length }
            val audioSize = audioList.sumOf { it.length }
            val total = videoSize + imageSize + audioSize
            val value = Utils.getSizeArray(total)
            withContext(Dispatchers.Main) {
                binding.tvSize.text = value[0]
                binding.tvUnit.text = value[1]
                binding.tvVideoSize.text = Utils.getSize(videoSize)
                binding.tvImageSize.text = Utils.getSize(imageSize)
                binding.tvAudioSize.text = Utils.getSize(audioSize)
                binding.tvNoVideo.visibility = if (videoList.isEmpty()) View.VISIBLE else View.GONE
                binding.tvNoImage.visibility = if (imageList.isEmpty()) View.VISIBLE else View.GONE
                val textColor = if (videoList.isEmpty()) getColor(R.color.color_aeb4bd) else getColor(R.color.colorPrimary)
                binding.tvVideoSize.setTextColor(textColor)
                binding.tvImageSize.setTextColor(textColor)
                binding.tvAudioSize.setTextColor(textColor)
                if (audioList.isNotEmpty()) {
                    val foundVoiceMessage = getString(R.string.found_voice_message).replace("3", "${audioList.size}")
                    binding.tvNoAudio.text = foundVoiceMessage
                }
                videoAdapter.updateData(videoList)
                imageAdapter.updateData(imageList)
            }
        }
    }

    private fun toDetail(list: List<FileBean>, type: Int, title: String) {
        if (list.isEmpty()) return
        list.forEach { it.isSelected = false }
        WhatsappCleanDetailActivity.start(this, list, type, title)
    }
}