package com.gh.gamecenter.forum.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.viewpager.widget.ViewPager;

import com.gh.common.util.DirectUtils;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.adapter.RecyclingPagerAdapter;
import com.gh.gamecenter.databinding.AskRecommendsSubjectItemBinding;
import com.gh.gamecenter.common.entity.LinkEntity;

import java.util.List;

/**
 * Created by khy on 1/04/18.
 */

public class ForumBannerPageAdapter extends RecyclingPagerAdapter {

    private Context mContext;

    private List<LinkEntity> mEntityList;

    private Boolean mIsTouchPage = false;
    private int mScrollState = ViewPager.SCROLL_STATE_IDLE;

    public ForumBannerPageAdapter(Context context, List<LinkEntity> entityList) {
        mContext = context;
        mEntityList = entityList;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        AskRecommendsSubjectItemBinding binding;
        if (convertView != null) {
            binding = AskRecommendsSubjectItemBinding.bind(convertView);
        } else {
            binding = AskRecommendsSubjectItemBinding.inflate(LayoutInflater.from(mContext), null, false);
        }
        LinkEntity entity = mEntityList.get(position % mEntityList.size());
        ImageUtils.display(binding.subjectIcon, entity.getIcon());
        binding.getRoot().setOnClickListener(v -> {
            MtaHelper.onEvent("论坛首页", "轮播图", entity.getText());
            DirectUtils.directToLinkPage(mContext, entity, "论坛首页", "轮播图", "");
        });

        binding.getRoot().setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
                mIsTouchPage = true;
            } else {
                mIsTouchPage = false;
            }
            return false;
        });
        return binding.getRoot();
    }

    public int getSize(List<LinkEntity> sourceList) {
        return sourceList == null ? 0 : sourceList.size();
    }

    public Boolean getTouchPage() {
        return mIsTouchPage || mScrollState != ViewPager.SCROLL_STATE_IDLE;
    }

    public void setScrollState(int scrollState) {
        this.mScrollState = scrollState;
    }

    @Override
    public int getCount() {
        if (mEntityList == null) return 0;
        if (mEntityList.size() == 1) return 1;
        return Integer.MAX_VALUE;
    }

    public int getActualFirstPositionInCenter() {
        if (mEntityList == null) return 0;
        int index = getCount() / 2;
        if (index % mEntityList.size() != 0) {
            index = index - (index % mEntityList.size());
        }
        return index;
    }
}
