package com.zxhyis.toolss.ui.page

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.cx.FileBean
import com.zxhyis.toolss.cx.FileHelps
import com.zxhyis.toolss.cx.FileHelps.toFormatSize
import com.zxhyis.toolss.cx.FileHelps.toFormatTime
import com.zxhyis.toolss.databinding.ActivityAllFilesBinding
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.startActivity

class AllFilesActivity : TopActivity<ActivityAllFilesBinding>() {
    var isEdit = false
    private var isSelectAll = false
    override fun getViewBinding1(): ActivityAllFilesBinding {
        return ActivityAllFilesBinding.inflate(layoutInflater)
    }

    companion object {

        const val images = 0
        const val videos = 1
        const val audio = 2
        const val empty = 3
        const val apks = 4
        const val doc = 5
        const val zip = 6
        const val large = 7
        fun launch(activity: Activity, type: Int) {
            activity.startActivity(Intent(activity, AllFilesActivity::class.java).apply {
                putExtra("type", type)
            })
        }
    }

    private val type by lazy {
        intent.getIntExtra("type", 7)
    }
    private val mData = mutableListOf<FileBean>()
    override fun init() {
//        checkPermission()
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        vb.root.updatePadding(top = BarUtils.getStatusBarHeight())
        vb.idDelete.isEnabled = false
        vb.idTitle.text = when (type) {
            large -> "Large Files"
            empty -> "Empty File"
            doc -> "Documents"
            images -> "Picture"
            videos -> "Video"
            audio -> "Audio"
            zip -> "ZIP"
            apks -> "APK"
            else -> ""
        }
        vb.idRlList.run {
            layoutManager = if (type in listOf(images, videos)) {
                GridLayoutManager(context, 3)
            } else {
                LinearLayoutManager(context)
            }
            adapter = mAdapter
        }
        initClick()
    }

    private fun initClick() {
        vb.idBack.setOnClick(javaClass.simpleName) {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finishToMain()
            }

        })

        vb.tvMenu.setOnClick(javaClass.simpleName) {
            isEdit = true
            vb.tvMenu.isVisible = false
            vb.idImgSelAll.isVisible = true
            vb.tvAll.isVisible = true
            vb.idClose.isVisible = true
            vb.idBack.isVisible = false
            vb.idDelete.isVisible = true
            mData.forEach { it.isSelect = false }
            mAdapter.notifyItemRangeChanged(0, mData.size, 1)
        }
        vb.idClose.setOnClick(javaClass.simpleName) {
            isEdit = false
            vb.tvMenu.isVisible = true
            vb.idBack.isVisible = true
            vb.idImgSelAll.isVisible = false
            vb.tvAll.isVisible = false
            vb.idClose.isVisible = false
            vb.idDelete.isVisible = false
            mData.forEach { it.isSelect = false }
            mAdapter.notifyItemRangeChanged(0, mData.size, 1)
        }
        vb.idImgSelAll.setOnClick(javaClass.simpleName) {
            if (mData.size > 0) {
                if (isSelectAll) {
                    isSelectAll = false
                    vb.idImgSelAll.setImageResource(R.drawable.iamge_unselected_all)
                } else {
                    isSelectAll = true
                    vb.idImgSelAll.setImageResource(R.drawable.image_selected_all)
                }
                mData.forEach { it.isSelect = isSelectAll }
                mAdapter.notifyItemRangeChanged(0, mData.size, 1)
                setTvStatus()
            }
        }
        vb.idDelete.setOnClick(javaClass.simpleName) {
            val ani = AnimationUtils.loadAnimation(this, R.anim.ad_ss)
            ani.interpolator = LinearInterpolator()
            vb.idImgLoad.startAnimation(ani)
            vb.idLlAdLoading.isVisible = true
            vb.idLlAdLoading.postDelayed({
                AdmobUtils.showInterstitialAd(this) {
                    vb.idLlAdLoading.isVisible = false
                    val list = FileHelps.fileList.toList().filter { it.isSelect }
                    if (list.isNotEmpty() && list.all { FileUtils.delete(it.path) }) {
                        FileHelps.fileList.removeAll(list)
                        mData.removeAll(list)
                        mAdapter.notifyDataSetChanged()
                        setTvStatus()
                        ToastUtils.showShort("Delete Successful")
                    } else {
                        ToastUtils.showShort("Delete failed.")
                    }
                }
//        MaxAdUtils.showMaxInterstitialAd(this, "interstitial_slot") {
//
//        }
            }, 2000)

        }


        vb.tvSet.setOnClick(javaClass.simpleName) {
            checkPermission(true)
        }
    }

    private fun setTvStatus() {
        val it = mData.filter { it.isSelect }
        vb.idDelete.isEnabled = it.isNotEmpty()
    }

    override fun onStart() {
        super.onStart()
        //Log.e("MXL", "onStart: ")
        checkPermission()
    }

    var isPause = false

    override fun onPause() {
        super.onPause()
        isPause = false
       // Log.e("MXL", "onPause: ")
    }

    override fun onResume() {
        super.onResume()
      //  Log.e("MXL", "onResume: ")
    }

    override fun onStop() {
        super.onStop()
   //     Log.e("MXL", "onStop: ")
        isPause = true
    }

    override fun onPermissionsResult(isGranted: Boolean) {
        if (isGranted) {
            vb.idLlNoPermisson.isVisible = false
            initList()
            if (!ifshowAd) {
                ifshowAd = true
                vb.root.postDelayed({
                    AdmobUtils.showInterstitialAd(this)
                }, kotlin.random.Random.nextLong(800, 1200))
            }

        } else {
            vb.idProcebar.isVisible = false
            vb.idLlNoPermisson.isVisible = true
        }
    }

    var ifshowAd = false
    private fun initList() {
        FileHelps.getFileList({

            FileHelps.fileList.toList().filter {
                if (it == null) {
                    true
                }
                when (type) {
                    images -> it.isImage()
                    videos -> it.isVideo()
                    doc -> it.isDoc()
                    audio -> it.isAudio()
                    empty -> it.isEmptyDir()
                    apks -> it.isApk()
                    zip -> it.isZip()
                    large -> it.isLargeFile()
                    else -> true
                } && it !in mData
            }.onEach { it.isSelect = false }.let {
                if (it.isNotEmpty()) {
                    vb.idProcebar.isVisible = false
                    mData.addAll(it)
                    mAdapter.notifyItemRangeInserted(mData.size, it.size)
                }
            }
        }, {
//            if (type !in listOf(images, videos)) {
//
//                AdmobUtils.showInterstitialAd(this)
//
//
//            }
            if (mData.isEmpty()) {
                vb.idProcebar.isVisible = false
                vb.idTvNoFile.isVisible = true
            }

        })
    }

    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 ivPlay: View?

            init {
                ivImage = view.findViewById(R.id.iv_image)
                tvName = view.findViewById(R.id.id_file_name)
                tvTime = view.findViewById(R.id.id_file_time)
                tvSize = view.findViewById(R.id.id_file_size)
                ivSelect = view.findViewById(R.id.id_img_sel)
                ivPlay = view.findViewById(R.id.id_play)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@AllFilesActivity).inflate(
                    if (type in listOf(images, videos)) {
                        R.layout.item_meiti
                    } else {
                        R.layout.item_files
                    }, parent, false
                )
                return ViewHolder(view)
            }

            override fun getItemCount() = mData.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = mData[position]
                if (item.isImage() || item.isVideo()) {
                    Glide.with(FileApp.fContext).load(item.path).into(holder.ivImage)
                } else {
                    holder.ivImage.setImageResource(
                        when {
                            item.isAudio() -> R.drawable.home_audio
                            item.isZip() -> R.drawable.home_zip
                            item.isApk() -> R.drawable.home_apk
                            item.isEmptyDir() -> R.drawable.home_empty_file
                            item.isLargeFile() -> R.drawable.home_largefiles
                            item.isDoc() -> R.drawable.home_documents
                            else -> R.drawable.home_audio
                        }
                    )
                }
                holder.tvName?.text = item.name
                holder.tvTime?.text = item.time.toFormatTime()
                holder.tvSize?.text = item.size.toFormatSize()
                holder.ivPlay?.isVisible = item.isVideo()
                holder.itemView.setOnClickListener {
                    if (isEdit) {
                        item.isSelect = !item.isSelect
                        notifyItemChanged(position, 1)
                        if (mData.all { it.isSelect }) {
                            isSelectAll = true
                            vb.idImgSelAll.setImageResource(R.drawable.image_selected_all)
                        } else {
                            isSelectAll = false
                            vb.idImgSelAll.setImageResource(R.drawable.iamge_unselected_all)
                        }
                        setTvStatus()
                    } else {
                        if (type == images) {
                            startActivity<PictureDetailActivity>("image_path" to item.path)
                        } else if (type == videos) {
                            val intent = Intent()
                            intent.action = Intent.ACTION_VIEW
                            intent.setDataAndType(Uri.parse(item.path), "video/*")
                            startActivity(intent)
                        }

                        // FileInfoActivity.launch(this@AllFilesActivity, type, item.path)
                    }

                }

                holder.ivPlay?.setOnClickListener {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.setDataAndType(Uri.parse(item.path), "video/*")
                    startActivity(intent)
                }
            }

            override fun onBindViewHolder(
                holder: ViewHolder,
                position: Int,
                payloads: MutableList<Any>
            ) {
                super.onBindViewHolder(holder, position, payloads)
                holder.ivSelect.isVisible = isEdit
                val item = mData[position]
                val isImage = type in listOf(images, videos)
                holder.ivSelect.setImageResource(
                    if (item.isSelect) {
                        if (isImage) R.drawable.image_selected else R.drawable.image_selected_all
                    } else {
                        if (isImage) R.drawable.image_unselected else R.drawable.iamge_unselected_all
                    }
                )
            }
        }
    }
}
