package com.guadou.ninegrid.nine_grid_layout

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import com.guadou.lib_baselib.engine.ImagePreviewUtils
import com.guadou.lib_baselib.ext.click
import com.guadou.ninegrid.ImageInfo
import com.guadou.ninegrid.ImageLoader
import com.guadou.ninegrid.NineGlideLoader
import com.guadou.ninegrid.R

/**
 * 默认的图片九宫格
 */
class SimpleImageViewNineGrid(context: Context?, attrs: AttributeSet?) : AbstractNineGridLayout<List<ImageInfo?>?>(context, attrs) {

    private lateinit var imageViews: Array<ImageView>
    private val mImageLoader: ImageLoader

    override fun fill() {
        fill(R.layout.item_image_grid)

        imageViews = findInChildren(R.id.iv_image, ImageView::class.java)
    }

    override fun render(activity: Activity, data: List<ImageInfo?>?) {

        data?.let {

            setSingleModeSize(it[0]?.getImageViewWidth()!!, it[0]?.getImageViewHeight()!!)

            setDisplayCount(it.size)

            for (i in it.indices) {
                val url = it[i]?.getThumbnailUrl()
                val imageView = imageViews[i]

                //使用自定义的Loader加载
                mImageLoader.onDisplayImage(context, imageView, url)

                //点击事件
                setClickListener(activity, imageView, i, it)
            }
        }

    }

    //设置内部每一个图片的点击事件,跳转到预览页面
    private fun setClickListener(activity: Activity, imageView: ImageView, position: Int, list: List<ImageInfo?>) {
        imageView.click {
            //开启多图预览
            ImagePreviewUtils.multipleImagePreview(
                activity,
                imageView,
                list.map { it?.thumbnailUrl as Any },
                position,
                R.drawable.layer_main_placeholder
            ) { popupView, position ->
                //当预览的图片滚动的时候需要选择是哪一个ImageView来生效了
                popupView.updateSrcView(imageViews[position])
            }
        }
    }

    //获取到指定索引的投票图片控件
    fun getImageView(index: Int): ImageView {
        return if (index >= imageViews.size) imageViews[index - 1] else imageViews[index]
    }

    //默认在xml中使用
    init {
        mImageLoader = NineGlideLoader()
    }

}