package com.yidianling.course;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import com.ydl.ydlcommon.adapter.CommonAdapter;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.yidianling.consultant.api.IConsultantService;
import com.yidianling.consultant.bean.GuideBean;
import com.yidianling.course.bean.Course;
import com.yidianling.course.widget.CourseItemNewView;

import java.util.ArrayList;
import java.util.List;

public class CourseNewListAdapter extends CommonAdapter<Course> {

    private Context context;
    private int guideImageIndex = 0;
    private int lastPosition = 0;
    private List<GuideBean> guideList = new ArrayList<>();

    public CourseNewListAdapter(Context context) {
        this.context = context;
        initGuideImageDate();
    }

    private void initGuideImageDate() {
        List<GuideBean> list = ModularServiceManager.INSTANCE.provide(IConsultantService.class).getGuideImage(8);
        if (list != null) {
            guideList.addAll(list);
        }
    }


    public void refreshLatPosition() {
        lastPosition = 0;
        guideImageIndex = 0;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = new CourseItemNewView(context);
        }
        ((CourseItemNewView) convertView).setData(mDataList.get(position));
        ((CourseItemNewView) convertView).setBottomLineVisible();
        if ((position + 1) % 10 == 0) {
            GuideBean bean = getGuideData(position);
            if (bean != null) {
                ((CourseItemNewView) convertView).setGuideData(bean.pic, bean.location);
            }
        } else {
            ((CourseItemNewView) convertView).setGuideGone();
        }
        return convertView;
    }

    private GuideBean getGuideData(int position) {
        if (guideList.size() == 0) {
            return null;
        }
        if (position % 3 == 0) {
            guideImageIndex = 0;
        }
        if (position % 3 == 1) {
            guideImageIndex = 1;
        }
        if (position % 3 == 2) {
            guideImageIndex = 2;
        }


        GuideBean bean = null;
        if (guideImageIndex >= guideList.size() - 1) {
            guideImageIndex = 0;
        }
        bean = guideList.get(guideImageIndex);

        return bean;
    }


    //修复 Android 4.4 Bug :cannot be cast to android.widget.AbsListView$LayoutParams
    @Override
    public boolean hasStableIds() {
        return true;
    }
}
