package com.ux.video.file.filerecovery.photo

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.ux.video.file.filerecovery.App
import com.ux.video.file.filerecovery.base.NewBaseAdapter
import com.ux.video.file.filerecovery.databinding.FileSpanCountThreeAdapterBinding
import com.ux.video.file.filerecovery.databinding.FileSpanCountTwoAdapterBinding
import com.ux.video.file.filerecovery.utils.Common
import com.ux.video.file.filerecovery.utils.CustomTextView
import com.ux.video.file.filerecovery.utils.ExtendFunctions.dpToPx
import com.ux.video.file.filerecovery.utils.ScanManager
import com.ux.video.file.filerecovery.utils.ScanRepository

class PhotoDisplayDateChildAdapter(
    mContext: Context,
    var mColumns: Int,
    var viewModel: ScanRepository,
    /**
     * 通知外层某天全选的按钮更新状态
     * @param updatePath 当前点击的item
     * @param addOrRemove 选中还是取消选中
     * @param dateAllSelected 这组数据是否全部选中（某一天）
     */
    var onSelectedUpdate: (updatePath: String, addOrRemove: Boolean, dateAllSelected: Boolean) -> Unit,
    var clickItem:(item:ResultPhotosFiles)-> Unit
) :
    NewBaseAdapter<ResultPhotosFiles>(mContext) {


    //日期组某一天的数据选择状态维护
    val dateSelectedMap = mutableSetOf<String>()

    companion object {
        private const val TYPE_TWO = 2
        private const val TYPE_THREE = 3
        private const val TYPE_FOUR = 4
    }


    fun setAllSelected(isAdd: Boolean) {
        data.forEach {
            addOrRemove(it.path.toString(), isAdd)
        }
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        return when (mColumns) {
            2 -> TYPE_TWO
            3 -> TYPE_THREE
            4 -> TYPE_FOUR
            else -> TYPE_THREE
        }
    }

    fun setColumns(int: Int) {
        mColumns = int
        notifyDataSetChanged()
    }

    /**
     * 设置View为正方形
     */
    private fun setHeight(view: View) {
        val layoutParams = view.layoutParams
        val screenWidth = view.context.resources.displayMetrics.widthPixels
        val i = (Common.itemSpacing).dpToPx(App.mAppContext) * (mColumns - 1)
        val itemSize =
            (screenWidth - i - 2 * Common.horizontalSpacing.dpToPx(App.mAppContext) )/ mColumns
        view.layoutParams = layoutParams.apply {
            height = itemSize
        }
    }

    override fun onCreateBinding(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            TYPE_TWO -> TwoHolder(
                FileSpanCountTwoAdapterBinding.inflate(
                    inflater,
                    parent,
                    false
                )
            )

            else -> ThreeHolder(
                FileSpanCountThreeAdapterBinding.inflate(
                    inflater,
                    parent,
                    false
                )
            )
        }

    }

    override fun onBind(
        holder: RecyclerView.ViewHolder,
        item: ResultPhotosFiles,
        viewType: Int
    ) {

        when (holder) {
            is TwoHolder -> holder.vb.run {
                initDateView(rootLayout, imageSelect, textSize, imageThumbnail, item)
            }

            is ThreeHolder -> holder.vb.run {
                initDateView(rootLayout, imageSelect, textSize, imageThumbnail, item)
            }
        }

    }

    class ThreeHolder(val vb: FileSpanCountThreeAdapterBinding) :
        RecyclerView.ViewHolder(vb.root)

    class TwoHolder(val vb: FileSpanCountTwoAdapterBinding) :
        RecyclerView.ViewHolder(vb.root)


    private fun initDateView(
        rootLayout: RelativeLayout,
        imageSelectStatus: ImageView,
        textSize: CustomTextView,
        imageThumbnail: ImageView,
        item: ResultPhotosFiles
    ) {
        item.run {
            viewModel.checkIsSelect(path.toString()).let {
                imageSelectStatus.isSelected = it
                addOrRemove(path.toString(), it)
            }
            imageSelectStatus.setOnClickListener {
                it.isSelected = !it.isSelected
                it.isSelected.let { newStatus ->
                    addOrRemove(path.toString(), newStatus)
                }
            }
            textSize.text = Common.formatFileSize(mContext, size)

            Glide.with(mContext)
                .load(targetFile)
                .apply(
                    RequestOptions()
                        .transform(CenterCrop(), RoundedCorners(8.dpToPx(mContext)))
                )
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable?>,
                        isFirstResource: Boolean
                    ): Boolean {
                        ScanManager.showLog(
                            "加载图片",
                            "-------path = ${path} file=${targetFile}"
                        )
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable,
                        model: Any,
                        target: Target<Drawable?>?,
                        dataSource: DataSource,
                        isFirstResource: Boolean
                    ): Boolean {

                        return false
                    }

                })
                .into(imageThumbnail)
            rootLayout.setOnClickListener { clickItem(item) }
            setHeight(rootLayout)

        }

    }

    private fun addOrRemove(path: String, boolean: Boolean) {
        if (boolean) {
            dateSelectedMap.add(path)
        } else {
            dateSelectedMap.remove(path)
        }
        onSelectedUpdate.invoke(path, boolean, dateSelectedMap.size == itemCount)
    }


}