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.ActivityScreenshotCleanBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import pokercc.android.expandablerecyclerview.ExpandableAdapter

class ScreenshotCleanActivity : BaseActivity2() {

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

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

    private lateinit var adapter: ScreenshotCleanAdapter
    private var total: Long = 0
    private var isSelectAll = false

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

    private fun initView() {
        adapter = ScreenshotCleanAdapter()
        adapter.selectionData.observe(this) { list ->
            isSelectAll = list.stream().allMatch(FileBean::isSelected)
            val selectionList = list.filter { it.isSelected }
            total = selectionList.sumOf { it.length }
            updateView(selectionList.isNotEmpty())
        }
        binding.expandableFiles.adapter = adapter
        val gridLayoutManager = GridLayoutManager(this, 3)
        gridLayoutManager.spanSizeLookup = MediaImageSpanLookup(3, adapter)
        binding.expandableFiles.layoutManager = gridLayoutManager

        binding.flBack.setOnClickListener { backPressed() }
        binding.llSelectAll.setOnClickListener {
            isSelectAll = !isSelectAll
            adapter.child.flatten().forEach { it.isSelected = isSelectAll }
            adapter.setData(adapter.group, adapter.child)
            total = adapter.child.flatten().filter { it.isSelected }.sumOf { it.length }
            updateView(isSelectAll)
        }
        binding.tvDelete.setOnClickListener {
            if (total <= 0) return@setOnClickListener
            DialogHelps.showDeleteDialog(this, binding.tvDelete) {
                showAnimationAd {
                    toCleanResult(total, getString(R.string.screenshot_clean))
                }
                cleanFiles(adapter.child.flatten())
            }
        }
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val screenFiles = MediaHelps.findScreenshotsFiles(this@ScreenshotCleanActivity)
            val total = screenFiles.values.toList().flatten().sumOf { it.length }
            val value = Utils.getSizeArray(total)
            withContext(Dispatchers.Main) {
                binding.tvSize.text = value[0]
                binding.tvUnit.text = value[1]
                adapter.setData(screenFiles.keys.toList(), screenFiles.values.toList())
                adapter.expandAllGroup()
                binding.ivEmpty.visibility = if (screenFiles.isEmpty()) View.VISIBLE else View.GONE
                binding.llBottom.visibility = if (screenFiles.isEmpty()) View.GONE else View.VISIBLE
            }
        }
    }

    private fun updateView(isSelection: Boolean) {
        binding.ivSelectAll.setImageResource(if (isSelectAll) R.mipmap.icon_yuan_junk_s else R.mipmap.icon_all_photo_off)
        binding.tvDelete.setBackgroundResource(if (isSelection) R.drawable.gradient_4 else R.drawable.gradient_not_clickable_4)
        val delete = getString(R.string.delete)
        val text = if (total > 0) "${delete} (${Utils.getSize(total)})" else delete
        binding.tvDelete.text = text
    }
}

internal class MediaImageSpanLookup(
    private val spanCount: Int,
    private val expandableAdapter: ExpandableAdapter<*>
) :
    GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        val viewType = expandableAdapter.getItemViewType(position)
        return if (expandableAdapter.isGroup(viewType)) spanCount else 1
    }

}