package com.ydl.ydlcommon.adapter.section;

import androidx.recyclerview.widget.RecyclerView;
import android.view.ViewGroup;

import com.yidianling.common.tools.LogUtil;

import java.util.ArrayList;

/**
 * Created by Jim on 2018/6/22 0022.
 */

public class SectionAdapter extends RecyclerView.Adapter {

    private final int TYPE_FOOTER = 0;
    private final int TYPE_BODY = 1;
    private final int TYPE_HEADER = 2;

    private ArrayList<Section> mSections = new ArrayList<>();

    public void addSection(Section section) {
        mSections.add(section);
    }

    /*找到对应position的section 根据viewType创建viewholder*/
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        for (Section section : mSections) {
            if (section.isBelongTo(viewType)) {
                viewHolder = section.onCreateViewHolder(parent, viewType);
                break;
            }
        }
        return viewHolder;
    }

    /*找到对应position的section，绑定对应数据*/
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int currentPosition = 0;
        for (Section section : mSections) {
            //section的实际数量
            int totalNum = section.getTotalDataNum();
            if (currentPosition <= position && position <= currentPosition + totalNum - 1) {
                section.bindViewHolder(holder, position - currentPosition);
                return;
            }
            currentPosition += totalNum;
        }
    }

    /*返回所有section Item数量的总和*/
    @Override
    public int getItemCount() {
        int totalCount = 0;
        for (Section section : mSections) {
            totalCount += section.getTotalDataNum();
        }
        return totalCount;
    }

    /**
     *
     * @return
     */
    public ArrayList<Section> getmSections(){
        return mSections;
    }

    /*
    * 1.找到该position对应的section
    * 2.返回section对应的viewType
    */
    @Override
    public int getItemViewType(int position) {
        int currentPosition = 0;
        for (Section section : mSections) {
            int totalNum = section.getTotalDataNum();
            if (currentPosition <= position && position <= currentPosition + totalNum - 1) {
                return section.getItemViewType(position - currentPosition);
            }
            currentPosition += totalNum;
        }
        LogUtil.d("error return -1");
        return -1;
    }

    /**
     * 更新Section数据
     * @param mSections
     */
    public void updataItems(ArrayList<Section> mSections){
        if (this.mSections == null){
            this.mSections = new ArrayList<>();
        }else {
            this.mSections.clear();
        }
        this.mSections.addAll(mSections);
    }

    /**
     * 清空Section数据
     */
    public void clearData() {
        if (mSections != null) {
            mSections.clear();
        }
    }

}
