package com.colorful.keyboard.theme

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.colorful.keyboard.theme.ad.AdsInsUtil
import com.colorful.keyboard.theme.config_adpter.DownloadAdapter
import com.colorful.keyboard.theme.databinding.ColorfulDownloadActivityBinding
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@OptIn(DelicateCoroutinesApi::class)
class DownloadsActivity : AppCompatActivity() {
    private lateinit var binding: ColorfulDownloadActivityBinding
    private var downloadAdapter = DownloadAdapter()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ColorfulDownloadActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        AdsInsUtil.showAdRandomModeAndTiming(this)
        initBar()
        initView()
        initData()

        AdsInsUtil.loadAllAdIsNotCached(this)
    }

    private fun initBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarView(binding.view)
        }
    }

    private fun initView() {
        binding.backBtn.setOnClickListener {
            onBackPressed()
        }
    }

    private fun initData() {
        binding.loadingLayout.visibility = View.VISIBLE
        GlobalScope.launch(Dispatchers.IO) {
            val downloads = App.downloadManager.getAllDownloadBeans()
            withContext(Dispatchers.Main) {
                binding.loadingLayout.visibility = View.GONE
                if (downloads.isNotEmpty()) {
                    binding.noDataLayout.visibility = View.GONE
                    downloadAdapter.submitList(downloads)
                    binding.rvPhotoIst.layoutManager = GridLayoutManager(this@DownloadsActivity, 3)
                    binding.rvPhotoIst.adapter = downloadAdapter
                    downloadAdapter.setOnItemClickListener { baseQuickAdapter, _, i ->
                        startActivity(
                            Intent(this@DownloadsActivity, ColorfulDetailsActivity::class.java)
                                .putExtra("title", baseQuickAdapter.getItem(i)!!.title)
                                .putExtra("key", baseQuickAdapter.getItem(i)!!.key)
                                .putExtra("url", baseQuickAdapter.getItem(i)!!.imgUrl)
                        )
                    }
                } else {
                    binding.noDataLayout.visibility = View.VISIBLE
                }
            }
        }
    }
}