package rowedto.jockeyedto.sheetedto.atticedto.allowedto

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.CarveedtoBinding
import com.bumptech.glide.Glide
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showDeletePermanentlyDialog
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showExitFunctionDialog
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showGerPermission
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.FileBean
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Crossingedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Everythingedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.checkStorePermission
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.requestStorePermission
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatSize
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatTime
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Flameedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spareedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto

class Smokeedto : Crossingedto<CarveedtoBinding>() {
    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, Smokeedto::class.java).apply {
                    putExtra(
                        "manager_type",
                        type
                    )
                })
        }
    }

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


    override fun initView() {
        Spareedto.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()
        }
        Scandaledto.admobMaxShowNativeAd(this, binding.tooledto,1)
        val layoutManager = when (title) {
            image -> GridLayoutManager(this, 4)
            else -> LinearLayoutManager(this)
        }
        binding.grabbededto.layoutManager = layoutManager
        binding.grabbededto.adapter = mAdapter
        binding.liberaledto.text = when (title) {
            video -> "Video Clean"
            image -> "Picture"
            audio -> "Audio"
            else -> ""
        }
        initListen()
    }

    private fun initListen() {
        binding.textureedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            when (title) {
                video -> {
                    showExitFunctionDialog {
                        if (it) {
                            Scandaledto.admobMaxShowInterstitialAd(this@Smokeedto, false) {
                                finishToMain()
                            }
                        } else {
                            finishToMain()
                        }

                    }
                }
            }

        }
        binding.effluxedto.setOnClickListener {
            if (isSelectAll) {
                isSelectAll = false
                binding.sightedto.text = "All"
                binding.retirementedto.setImageResource(R.mipmap.excessedto)
            } else {
                isSelectAll = true
                binding.sightedto.text = "Cancel"
                binding.retirementedto.setImageResource(R.mipmap.nearestedto)
            }
            mFileList.forEach { it.isSelect = isSelectAll }
            mAdapter.notifyItemRangeChanged(0, mFileList.size, 1)
            setStatus()
        }
        binding.mathematicsedto.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 {
                Scandaledto.admobMaxShowInterstitialAd(this)  {
                    val list = mFileList.filter { it.isSelect }
                    val path = mutableListOf<String>()
                    list.forEach {
                        path.add(it.path)
                    }
                    Everythingedto.updateMediaStore(this, path)
                    if (list.isNotEmpty() && list.all {
                           Flameedto.delete(
                                it.path
                            )
                        }) {
                        Everythingedto.fileList.removeAll(list)
                        mFileList.removeAll(list)
                        mAdapter.notifyDataSetChanged()
                        setStatus()
                    } else {
                        Toast.makeText(this, "Delete failed.", Toast.LENGTH_SHORT).show()
                    }
                }
            }

        }

    }

    private fun getList() {
        Everythingedto.getFilesByType(this) {
            val list = Everythingedto.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.onionedto.isVisible = false
                    binding.mathematicsedto.isVisible = true
                    mFileList.addAll(it)
                    mAdapter.notifyItemRangeInserted(mFileList.size, it.size)
                } else {
                    binding.onionedto.isVisible = true
                    binding.mathematicsedto.isVisible = false
                }
            }
        }
    }


    private fun setStatus() {

        val it = mFileList.filter { it.isSelect }
        binding.mathematicsedto.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.meansedto)
                tvName = view.findViewById(R.id.hearedto)
                tvTime = view.findViewById(R.id.seminaredto)
                tvSize = view.findViewById(R.id.agreementedto)
                ivSelect = view.findViewById(R.id.clusteredto)
                idcardView = view.findViewById(R.id.falledto)
                idaudioView = view.findViewById(R.id.shallowedto)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@Smokeedto).inflate(
                    if (title == image) {
                        R.layout.pleadedto
                    } else {
                        R.layout.lilyedto
                    }, 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@Smokeedto).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.sightedto.text = "Cancel"
                        binding.retirementedto.setImageResource(R.mipmap.nearestedto)
                    } else {
                        isSelectAll = false
                        binding.sightedto.text = "All"
                        binding.retirementedto.setImageResource(R.mipmap.excessedto)
                    }
                    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.nearestedto
                    } else {
                        R.mipmap.excessedto
                    }
                )
            }
        }
    }
}