package com.wanyue.common.adapter;

import android.content.Context;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.wanyue.common.utils.FaceUtil;
import com.wanyue.common.R;
import com.wanyue.common.interfaces.OnFaceClickListener;

import org.jetbrains.annotations.NotNull;

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

/**
 * Created by cxf on 2018/7/11.
 * 聊天表情的ViewPager Adapter
 */

public class ImChatFacePagerAdapter extends PagerAdapter {

    private List<View> mViewList;
    private  int mFaceCount = 20;//每页20个表情

    public ImChatFacePagerAdapter(Context context, int faceCount,OnFaceClickListener onFaceClickListener) {
        mFaceCount=faceCount;
        LayoutInflater inflater = LayoutInflater.from(context);

        mViewList = new ArrayList<>();
        List<String> faceList = FaceUtil.getFaceList();
        int fromIndex = 0;
        int size = faceList.size();
        int pageCount = size / mFaceCount;
        if (size % mFaceCount > 0) {
            pageCount++;
            for (int i = 0, count = pageCount * mFaceCount - size; i < count; i++) {
                faceList.add("");
            }
        }
        int spanCount=mFaceCount/3;
        for (int i = 0; i < pageCount; i++) {
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.view_chat_face_page, null, false);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new GridLayoutManager(context, spanCount, GridLayoutManager.VERTICAL, false));
            int endIndex = fromIndex + mFaceCount;
            List<String> list = new ArrayList<>();
            for (int j = fromIndex; j < endIndex; j++) {
                list.add(faceList.get(j));
            }
            list.add("<");
            recyclerView.setAdapter(new ImChatFaceAdapter(list, inflater, onFaceClickListener));
            mViewList.add(recyclerView);
            fromIndex = endIndex;
        }
    }





    @Override
    public int getCount() {
        return mViewList.size();
    }

    @Override
    public boolean isViewFromObject(@Nullable View view, @Nullable Object object) {
        return view == object;
    }

    @NotNull
    @Override
    public Object instantiateItem(@Nullable ViewGroup container, int position) {
        View view = mViewList.get(position);
        container.addView(view);
        return view;
    }


    @Override
    public void destroyItem(@Nullable ViewGroup container, int position, @Nullable Object object) {
        container.removeView(mViewList.get(position));
    }

    public int getFaceCount() {
        return mFaceCount;
    }

    public void setFaceCount(int faceCount) {
        mFaceCount = faceCount;
    }
}
