package com.yidianling.home.ui.view

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.yidianling.home.R
import com.yidianling.home.event.IHomeBaseEvent
import com.yidianling.home.model.bean.HomeCourseBean
import kotlinx.android.synthetic.xlzx.home_course_view.view.*

/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 课程*成长模块
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/13
 */
class HomeCourseView(private val mContext: Context, private var homeEvent: IHomeBaseEvent?) :
    LinearLayout(mContext) {

    private var cacheList: ArrayList<HomeCourseBean.ListBean> = ArrayList()

    init {
        initView()
    }

    private fun initView() {
        orientation = VERTICAL
        val params = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        layoutParams = params
        View.inflate(mContext, R.layout.home_course_view, this)
        homeModuleCourseViewHomeCommonTitleView.setTitle("未知潜能")
        homeModuleCourseViewHomeCommonTitleView.setMoreText("更多课程")
        homeModuleCourseViewHomeCommonTitleView.setOnClickListener {
            homeEvent?.courseMreClick()
        }
    }

    fun initData(list: List<HomeCourseBean.ListBean>?) {
        //添加View
        if (list == null) {
            return
        }
        if (cacheList.size != list?.size) {
            cacheList.clear()
            cacheList.addAll(list!!)
            updateHomeCourseItemViewNumber()
        }
        //刷新数据
        for (index in 0 until homeModuleCourseViewScrollLL.childCount) {
            val itemView = homeModuleCourseViewScrollLL.getChildAt(index)
            if (itemView is HomeCourseItemView) {
                itemView.updateData(cacheList[index])
            }
        }
    }

    /**
     * 更新itemView的数量以适应新的数据集
     */
    private fun updateHomeCourseItemViewNumber() {
        var childCountRecord = homeModuleCourseViewScrollLL.childCount //减1是因为第一个子View是标题View
        while (cacheList.size > childCountRecord) {
            homeModuleCourseViewScrollLL.addView(HomeCourseItemView(mContext, homeEvent))
            childCountRecord++
        }
        while (cacheList.size < childCountRecord && homeModuleCourseViewScrollLL.getChildAt(childCountRecord - 1) is HomeCourseItemView) {
            homeModuleCourseViewScrollLL.removeViewAt(childCountRecord - 1)
            childCountRecord--
        }
    }
}