package rallyedto.finishedto.sheepedto.extraterrestrialedto

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.addCallback
import androidx.cardview.widget.CardView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.base.datarecovery.R
import com.base.datarecovery.databinding.StrideedtoBinding
import com.bumptech.glide.Glide
import rallyedto.battleedto.acresedto.Circulationedto
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatSize
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatTime
import rallyedto.battleedto.acresedto.Lemonedto
import rallyedto.battleedto.acresedto.Napedto.checkStorePermission
import rallyedto.battleedto.acresedto.Napedto.requestStorePermission
import rallyedto.farewelledto.Technologyedto.showDeletePermanentlyDialog
import rallyedto.farewelledto.Technologyedto.showExitFunctionDialog
import rallyedto.farewelledto.Technologyedto.showGerPermission
import rallyedto.policeedto.huntedto.FileBean
import rallyedto.sunedto.tumouredto.majorityedto.loseedto.Togetheredto
import rallyedto.talledto.blewedto.Islandedto
import rallyedto.talledto.blewedto.Sketchedto

class Discussedto : Lemonedto<StrideedtoBinding>() {
    private var isSelectAll = false
    private val mFileList = mutableListOf<FileBean>()


    companion object {

        const val video = 0
        const val image = 1
        const val audio = 2
        fun launch(activity: Activity, type: Int) {
            activity.startActivity(
                Intent(activity, Discussedto::class.java).apply {
                    putExtra(
                        "manager_type",
                        type
                    )
                })
        }
    }

    private val title by lazy {
        intent.getIntExtra("manager_type", 0)
    }
    override val binding: StrideedtoBinding by lazy {
        StrideedtoBinding.inflate(layoutInflater)
    }


    override fun initView() {
        Islandedto.setStatusBarLightMode(this, true)
        initViews()
    }

    private fun initViews() {
        if (!checkStorePermission()) {
            showGerPermission(tittle = "Storage Permission Required",
                deny = { finishToMain() },
                allow = {
                    requestStorePermission(launcher, result = {
                        if (it) {
                            getList()
                        } else {
                            finishToMain()
                        }
                    })
                })
        } else {
            getList()
        }
        Togetheredto.showNativeAd(this,binding.jeweledto)
        val layoutManager = when (title) {
            image -> GridLayoutManager(this, 4)
            else -> LinearLayoutManager(this)
        }
        binding.touristedto.layoutManager = layoutManager
        binding.touristedto.adapter = mAdapter
        binding.liltedto.text = when (title) {
            video -> "Video Clean"
            image -> "Picture"
            audio -> "Audio"
            else -> ""
        }
        initListen()
    }

    private fun initListen() {
        binding.compareedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            when (title) {
                video -> {
                    showExitFunctionDialog {
                        admobMaxShowInterstitialAd(isShow = Togetheredto.isShowAdBackInter()) {
                            finishToMain()
                        }

                    }
                }
            }

        }
        binding.taxedto.setOnClickListener {
            if (isSelectAll) {
                isSelectAll = false
                binding.handicapedto.text = "All"
                binding.enhanceedto.setImageResource(R.mipmap.walkedto)
            } else {
                isSelectAll = true
                binding.handicapedto.text = "Cancel"
                binding.enhanceedto.setImageResource(R.mipmap.junioredto)
            }
            mFileList.forEach { it.isSelect = isSelectAll }
            mAdapter.notifyItemRangeChanged(0, mFileList.size, 1)
            setStatus()
        }
        binding.basketedto.setOnClickListener {
//            val desc = when (title) {
//                image -> "You have selected ${mFileList.filter { it.isSelect }.size} album pictures which will not be retrieved after deletion"
//                else -> "Confirm to delete this ${mFileList.filter { it.isSelect }.size} item"
//            }
            showDeletePermanentlyDialog {
                admobMaxShowInterstitialAd(true)  {
                    val list = mFileList.filter { it.isSelect }
                    val path = mutableListOf<String>()
                    list.forEach {
                        path.add(it.path)
                    }
                    Circulationedto.updateMediaStore(this, path)
                    if (list.isNotEmpty() && list.all {
                           Sketchedto.delete(
                                it.path
                            )
                        }) {
                        Circulationedto.fileList.removeAll(list)
                        mFileList.removeAll(list)
                        mAdapter.notifyDataSetChanged()
                        setStatus()
                    } else {
                        Toast.makeText(this, "Delete failed.", Toast.LENGTH_SHORT).show()
                    }
                }
            }

        }

    }

    private fun getList() {
        Circulationedto.getFilesByType(this) {
            val list = Circulationedto.fileList.toList().filter {
                when (title) {
                    video -> it.isVideo()
                    image -> it.isImage()
                    audio -> it.isAudio()
                    else -> true
                } && it !in mFileList
            }
            list.let {
                if (it.isNotEmpty()) {
                    binding.biscuitedto.isVisible = false
                    binding.basketedto.isVisible = true
                    mFileList.addAll(it)
                    mAdapter.notifyItemRangeInserted(mFileList.size, it.size)
                } else {
                    binding.biscuitedto.isVisible = true
                    binding.basketedto.isVisible = false
                }
            }
        }
    }


    private fun setStatus() {

        val it = mFileList.filter { it.isSelect }
        binding.basketedto.isEnabled = it.isNotEmpty()
    }

    private val mAdapter by lazy {
        class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val ivImage: ImageView
            val tvName: TextView?
            val tvTime: TextView?
            val tvSize: TextView?
            val ivSelect: ImageView
            val idcardView: CardView?
            val idaudioView: ImageView?

            init {
                ivImage = view.findViewById(R.id.butterflyedto)
                tvName = view.findViewById(R.id.nurseryedto)
                tvTime = view.findViewById(R.id.flockedto)
                tvSize = view.findViewById(R.id.seatedto)
                ivSelect = view.findViewById(R.id.childrenedto)
                idcardView = view.findViewById(R.id.sumedto)
                idaudioView = view.findViewById(R.id.libertyedto)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@Discussedto).inflate(
                    if (title == image) {
                        R.layout.neighborhoodedto
                    } else {
                        R.layout.summeredto
                    }, parent, false
                )
                return ViewHolder(view)
            }

            override fun getItemCount() = mFileList.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = mFileList[position]
                if (title == video) {
                    holder.idcardView?.isVisible = true
                    holder.idaudioView?.isVisible = false
                } else if (title == audio) {
                    holder.idcardView?.isVisible = false
                    holder.idaudioView?.isVisible = true
                }
                if (item.isImage() || item.isVideo()) {
                    Glide.with(this@Discussedto).load(item.path).into(holder.ivImage)
                }
                holder.tvName?.text = item.name
                holder.tvTime?.text = item.time.toFormatTime()
                holder.tvSize?.text = item.size.toFormatSize()
                holder.itemView.setOnClickListener {
                    item.isSelect = !item.isSelect
                    notifyItemChanged(position, 1)
                    if (mFileList.all { it.isSelect }) {
                        isSelectAll = true
                        binding.handicapedto.text = "Cancel"
                        binding.enhanceedto.setImageResource(R.mipmap.junioredto)
                    } else {
                        isSelectAll = false
                        binding.handicapedto.text = "All"
                        binding.enhanceedto.setImageResource(R.mipmap.walkedto)
                    }
                    setStatus()
                }


            }

            override fun onBindViewHolder(
                holder: ViewHolder,
                position: Int,
                payloads: MutableList<Any>
            ) {
                super.onBindViewHolder(holder, position, payloads)
                val item = mFileList[position]
                holder.ivSelect.setImageResource(
                    if (item.isSelect) {
                        R.mipmap.junioredto
                    } else {
                        R.mipmap.walkedto
                    }
                )
            }
        }
    }
}