package com.yidianling.tests.home.widget

import android.content.Context
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import android.view.View
import android.widget.ImageView
import com.ydl.ydl_image.module.GlideApp
import com.yidianling.tests.R
import com.yidianling.tests.home.bean.TestHomeBodyBean
import com.yidianling.tests.home.event.ITestHomeEvent
import java.util.*

/**
 * @author yuanwai
 * @描述:测评首页banner viewpager适配器
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/7/27
 */
class TestHomeBannerAdapter(
        /**
         * 数据集合
         */
        var mDataList: List<TestHomeBodyBean>,
        var mContext: Context,
        var testHomeEvent: ITestHomeEvent) : PagerAdapter() {

    private var mImageViews: List<ImageView>? = null

    /**
     * 初始化
     */
    init {
        updataImage()
    }

    /**
     * 更新图片集合 todo 待优化 yuanwai 2018/07/27
     */
    private fun updataImage() {
        if (null == mImageViews || mImageViews!!.isEmpty()) {
            mImageViews = ArrayList()
        } else {
            (mImageViews as ArrayList).clear()
        }
        var count = mDataList.size - 1
        for (index in 0..count) {
            var item = mDataList[index]
            val imageView = ImageView(mContext)
            imageView.scaleType = ImageView.ScaleType.FIT_XY
            GlideApp.with(mContext)
                    .load(item.bannerImageUrl)
                    .placeholder(R.drawable.tests_testhome_banner_nor)
                    .centerCrop()
                    .into(imageView)
            (mImageViews as ArrayList<ImageView>).add(imageView)
            imageView.setOnClickListener {
                testHomeEvent.bannerClick(item.bannerLinkUrl, index, item.bannerName)
            }
        }
    }

    override fun getCount(): Int {
        return mDataList.size
    }

    /**
     * 数据更新
     */
    fun updataItems(items: List<TestHomeBodyBean>) {
        if (items.isEmpty()) {
            return
        }

        if (null == mDataList) {
            mDataList = ArrayList()
        } else {
            (mDataList as ArrayList).clear()
        }
        (mDataList as ArrayList<TestHomeBodyBean>).addAll(items)
        updataImage()
        notifyDataSetChanged()
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object`
    }

    override fun destroyItem(container: View, position: Int, `object`: Any) {

    }

    override fun instantiateItem(container: View, position: Int): Any {
        try {
            (container as ViewPager).addView(mImageViews!!.get(position % mDataList.size), 0)
        } catch (e: Exception) {

        }

        return mImageViews!!.get(position % mDataList.size)
    }
}