package com.base.datarecovery.activity.videomanager

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.ads.AdmobMaxHelper
import com.base.datarecovery.bean.FileBean
import com.base.datarecovery.databinding.ActivityLayoutManagerBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.FileHelp
import com.base.datarecovery.help.KotlinExt.toFormatSize
import com.base.datarecovery.help.KotlinExt.toFormatTime
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.help.PermissionHelp.requestStorePermission
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.NewFileUtils
import com.base.datarecovery.view.DialogViews.showDeletePermanentlyDialog
import com.base.datarecovery.view.DialogViews.showExitFunctionDialog
import com.base.datarecovery.view.DialogViews.showGerPermission
import com.bumptech.glide.Glide

class ManagerActivity : BaseActivity<ActivityLayoutManagerBinding>() {
    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, ManagerActivity::class.java).apply {
                    putExtra(
                        "manager_type",
                        type
                    )
                })
        }
    }

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


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

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

                    }
                }
            }

        }
        binding.idLlTop.setOnClickListener {
            if (isSelectAll) {
                isSelectAll = false
                binding.idTvTopAll.text = "All"
                binding.idImgTopSelect.setImageResource(R.mipmap.weixuan)
            } else {
                isSelectAll = true
                binding.idTvTopAll.text = "Cancel"
                binding.idImgTopSelect.setImageResource(R.mipmap.xuanzhong)
            }
            mFileList.forEach { it.isSelect = isSelectAll }
            mAdapter.notifyItemRangeChanged(0, mFileList.size, 1)
            setStatus()
        }
        binding.idTvDelete.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 {
                AdmobMaxHelper.admobMaxShowInterstitialAd(this)  {
                    val list = mFileList.filter { it.isSelect }
                    val path = mutableListOf<String>()
                    list.forEach {
                        path.add(it.path)
                    }
                    FileHelp.updateMediaStore(this, path)
                    if (list.isNotEmpty() && list.all {
                           NewFileUtils.delete(
                                it.path
                            )
                        }) {
                        FileHelp.fileList.removeAll(list)
                        mFileList.removeAll(list)
                        mAdapter.notifyDataSetChanged()
                        setStatus()
                    } else {
                        Toast.makeText(this, "Delete failed.", Toast.LENGTH_SHORT).show()
                    }
                }
            }

        }

    }

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


    private fun setStatus() {

        val it = mFileList.filter { it.isSelect }
        binding.idTvDelete.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.id_icon)
                tvName = view.findViewById(R.id.id_tv_name)
                tvTime = view.findViewById(R.id.id_tv_time)
                tvSize = view.findViewById(R.id.id_tv_size)
                ivSelect = view.findViewById(R.id.id_img_select)
                idcardView = view.findViewById(R.id.id_cardview)
                idaudioView = view.findViewById(R.id.id_audio_img)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@ManagerActivity).inflate(
                    if (title == image) {
                        R.layout.item_layout_image
                    } else {
                        R.layout.item_layout_video
                    }, 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@ManagerActivity).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.idTvTopAll.text = "Cancel"
                        binding.idImgTopSelect.setImageResource(R.mipmap.xuanzhong)
                    } else {
                        isSelectAll = false
                        binding.idTvTopAll.text = "All"
                        binding.idImgTopSelect.setImageResource(R.mipmap.weixuan)
                    }
                    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.xuanzhong
                    } else {
                        R.mipmap.weixuan
                    }
                )
            }
        }
    }
}