package com.ux.video.file.filerecovery.sort

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.lifecycle.ViewModel
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.R
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.databinding.OneAudioItemBinding
import com.ux.video.file.filerecovery.databinding.OneDocumentsItemBinding
import com.ux.video.file.filerecovery.db.ResultDataFiles
import com.ux.video.file.filerecovery.db.duration
import com.ux.video.file.filerecovery.db.targetFile
import com.ux.video.file.filerecovery.recovery.ui.recoveryphoto.RecoveryPhotoViewModel
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.FileType
import com.ux.video.file.filerecovery.utils.ScanManager


/**
 * 排序页面显示 、已经恢复的文件页面显示
 */
class SortDisplayChildAdapter(
    mContext: Context,
    var fileType: FileType,
    var mColumns: Int,
    var viewModel: ViewModel? = null,
    /**
     * 通知外层某天全选的按钮更新状态
     * @param updatePath 当前点击的item
     * @param addOrRemove 选中还是取消选中
     * @param dateAllSelected 这组数据是否全部选中（某一天）
     */
    var onSelectedUpdate: (resultDataFiles: ResultDataFiles, addOrRemove: Boolean, dateAllSelected: Boolean) -> Unit,
    var hideThumbnailsUpdate: (dateAllSelected: Boolean) -> Unit,
    var clickItem: (item: ResultDataFiles) -> Unit
) :
    NewBaseAdapter<ResultDataFiles>(mContext) {


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


    companion object {
        //视频和图片支持布局切换 2/3/4列
        private const val TYPE_TWO = 2
        private const val TYPE_THREE = 3
        private const val TYPE_FOUR = 4

        private const val TYPE_AUDIO = 5
        private const val TYPE_DOCUMENTS = 6
    }

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

    override fun getItemViewType(position: Int): Int {
        when (fileType) {
            FileType.AUDIO -> {
                return TYPE_AUDIO
            }

            FileType.DOCUMENT -> {
                return TYPE_DOCUMENTS
            }

            else -> {
                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_AUDIO -> AudioHolder(
                OneAudioItemBinding.inflate(
                    inflater,
                    parent,
                    false
                )
            )

            TYPE_DOCUMENTS -> DocumentsHolder(
                OneDocumentsItemBinding.inflate(
                    inflater,
                    parent,
                    false
                )
            )

            TYPE_TWO -> TwoHolder(
                FileSpanCountTwoAdapterBinding.inflate(
                    inflater,
                    parent,
                    false
                )
            )

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

    }

    override fun onBind(
        holder: RecyclerView.ViewHolder,
        item: ResultDataFiles,
        viewType: Int
    ) {
        when (holder) {
            is TwoHolder -> holder.vb.run {
                initDateView(rootLayout, imageSelect, textSize, imageThumbnail, item, imageType)
            }

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

            is AudioHolder -> {
                item.run {
                    holder.vb.let {
                        it.textName.text = name
                        it.textDuration.text = Common.formatDuration(duration())
                        it.textSize.text = sizeString

                        initAudioDocuments(it.imageSelect, this)
                        it.constraintLayout.setOnClickListener {
                            clickItem(this)
                        }

                    }
                }
            }

            is DocumentsHolder -> {
                item.run {
                    holder.vb.let {
                        it.textName.text = name
                        it.textDate.text = Common.getItemMonthDay(lastModified)
                        it.textSize.text = sizeString
                        targetFile().let { file ->
                            it.imageIcon.setImageResource(Common.getFileIconRes(file))
                        }

                        initAudioDocuments(it.imageSelect, this)

                        it.constraintLayout.setOnClickListener {
                            clickItem(this)
                        }
                    }


                }

            }
        }

    }

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

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

    class AudioHolder(val vb: OneAudioItemBinding) :
        RecyclerView.ViewHolder(vb.root)

    class DocumentsHolder(val vb: OneDocumentsItemBinding) :
        RecyclerView.ViewHolder(vb.root)


    private fun initAudioDocuments(imageSelect: ImageView, item: ResultDataFiles) {

        viewModel?.let {
            if (it is SortingViewModel) {
                it.checkIsSelect(item)
            } else {
                it as RecoveryPhotoViewModel
                it.checkIsSelect(fileType, item)
            }.let { isSelected ->
                imageSelect.isSelected = isSelected == true
                addOrRemove(item, isSelected == true)

            }
        }

        imageSelect.setOnClickListener {
            it.isSelected = !it.isSelected
            it.isSelected.let { newStatus ->
                addOrRemove(item, newStatus)
            }
        }
    }

    private fun initDateView(
        rootLayout: RelativeLayout,
        imageSelectStatus: ImageView,
        textSize: CustomTextView,
        imageThumbnail: ImageView,
        item: ResultDataFiles,
        imageType: ImageView
    ) {
        item.run {
            initAudioDocuments(imageSelectStatus, this)
            textSize.text = sizeString
            imageType.setImageResource(
                when (fileType) {
                    FileType.PHOTO -> R.drawable.icon_type_photo
                    FileType.VIDEO -> R.drawable.icon_type_video
                    else -> R.drawable.icon_type_photo
                }
            )
            Glide.with(mContext)
                .load(targetFile())
                .apply(
                    RequestOptions()
                        .transform(CenterCrop(), RoundedCorners(8.dpToPx(mContext)))
                )
                .error(R.drawable.photo_place_holder)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable?>,
                        isFirstResource: Boolean
                    ): Boolean {
                        ScanManager.showLog(
                            "加载图片",
                            "-------path = ${path}  e=${e?.message}"
                        )
                        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(resultDataFiles: ResultDataFiles, boolean: Boolean) {
        if (boolean) {
            dateSelectedMap.add(resultDataFiles)
        } else {
            dateSelectedMap.remove(resultDataFiles)
        }
        onSelectedUpdate.invoke(resultDataFiles, boolean, dateSelectedMap.size == data.size)

    }


}