package com.gh.gamecenter.info;

import android.content.Context;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.common.constant.Config;
import com.gh.common.util.NewsUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.NewsFooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsTextViewHolder;
import com.gh.gamecenter.databinding.NewsFooterItemBinding;
import com.gh.gamecenter.databinding.NewsTextItemBinding;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.adapter.BaseRecyclerAdapter;

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

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * Created by khy on 2017/4/7.
 * 资讯-攻略适配器
 */
class StrategyAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private OnRequestCallBackListener mCallBackListener;
    private OnListClickListener mListListener;

    private List<NewsEntity> mNewsList;

    private boolean isRemove;
    private boolean isLoading;
    private boolean isNetworkError;

    private int mPage;

    StrategyAdapter(Context context, OnRequestCallBackListener callBackListener, OnListClickListener listListener) {
        super(context);
        this.mCallBackListener = callBackListener;
        this.mListListener = listListener;
        mNewsList = new ArrayList<>();

        isLoading = false;
        isRemove = false;
        isNetworkError = false;
        mPage = 1;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 1) {
            return new NewsTextViewHolder(NewsTextItemBinding.inflate(mLayoutInflater, parent, false), mListListener);
        } else {
            return new NewsFooterViewHolder(NewsFooterItemBinding.inflate(mLayoutInflater, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof NewsTextViewHolder) {
            final NewsTextViewHolder viewHolder = (NewsTextViewHolder) holder;
            final NewsEntity newsEntity = mNewsList.get(position);
            viewHolder.setClickData(newsEntity);
            if (!TextUtils.isEmpty(newsEntity.getType())) {
                if (position == 0 && newsEntity.getPriority() != 0) {
                    viewHolder.binding.newsTextType.setText(R.string.article_top);
                    newsEntity.setType(mContext.getString(R.string.article_top));
                } else if (newsEntity.getPriority() != 0) {
                    viewHolder.binding.newsTextType.setText(R.string.article_hot);
                    newsEntity.setType(mContext.getString(R.string.article_hot));
                } else {
                    viewHolder.binding.newsTextType.setText(newsEntity.getType());
                }
                viewHolder.binding.newsTextType.setVisibility(View.VISIBLE);
            } else {
                viewHolder.binding.newsTextType.setVisibility(View.GONE);
            }

            viewHolder.binding.newsTextType.setBackgroundResource(NewsUtils.getDrawableIdByType(newsEntity.getType()));
            viewHolder.binding.newsTextType.setText(newsEntity.getType());
            viewHolder.binding.newsTextTitle.setText(newsEntity.getTitle());
            viewHolder.binding.newsTextTitle.setTextColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.title));
            viewHolder.binding.newsTextLine.setBackgroundColor(ContextCompat.getColor(viewHolder.itemView.getContext(), R.color.cutting_line));
            viewHolder.itemView.setBackground(ContextCompat.getDrawable(viewHolder.itemView.getContext(), R.drawable.reuse_listview_item_style));
        } else {
            final NewsFooterViewHolder footerViewHolder = ((NewsFooterViewHolder) holder);
            footerViewHolder.binding.newsFooterHint.setTextColor(ContextCompat.getColor(footerViewHolder.itemView.getContext(), R.color.content));
            if (isRemove) {
                footerViewHolder.binding.newsFooterHint.setText(R.string.loading_complete);
                footerViewHolder.binding.newsFooterLoading.setVisibility(View.GONE);
            } else if (isNetworkError) {
                footerViewHolder.binding.newsFooterHint.setText(R.string.loading_error_network);
                footerViewHolder.binding.newsFooterLoading.setVisibility(View.GONE);
            } else {
                footerViewHolder.binding.newsFooterHint.setText(R.string.loading);
                footerViewHolder.binding.newsFooterLoading.setVisibility(View.VISIBLE);
            }
            footerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isNetworkError) {
                        isNetworkError = false;
                        footerViewHolder.binding.newsFooterHint.setText(R.string.loading);
                        footerViewHolder.binding.newsFooterLoading.setVisibility(View.VISIBLE);
                        addList();
                    }
                }
            });
        }
    }

    public void addList() {
        isLoading = true;
        RetrofitManager.getInstance()
                .getApi()
                .getArticleList(UrlFilterUtils.getFilterQuery("type_group", "攻略"), mPage)
                .map(newsEntities -> {
                    Config.filterPluginArticle(newsEntities);
                    return NewsUtils.removeDuplicateData(mNewsList, newsEntities);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<NewsEntity>>() {
                    @Override
                    public void onResponse(List<NewsEntity> response) {
                        if (response.size() != 0) {
                            mNewsList.addAll(response);
                            if (mNewsList.size() <= 20) {
                                notifyDataSetChanged();
                            } else {
                                notifyItemRangeInserted(mNewsList.size() - response.size(), response.size());
                            }
                            notifyItemChanged(getItemCount() - response.size() - 2);
                        }

                        if (response.size() < 20) {
                            isRemove = true;
                            notifyItemChanged(getItemCount() - 1);
                        }

                        if (mNewsList.size() == 0) {
                            mCallBackListener.loadEmpty();
                        } else {
                            mCallBackListener.loadDone();
                        }

                        mPage++;
                        isLoading = false;
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        isLoading = false;
                        if (mPage == 1) {
                            mCallBackListener.loadError();
                        } else {
                            isNetworkError = true;
                            notifyItemChanged(getItemCount() - 1);
                        }

                    }
                });
    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public int getItemCount() {
        return mNewsList.size() + 1;
    }

    public boolean isCanLoading() {
        return (!isNetworkError && !isLoading && !isRemove);
    }
}
