package com.gh.gamecenter.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import com.gh.common.constant.Config;
import com.gh.common.util.DataCollectionUtils;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.common.util.NewsUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.common.utils.TextHelper;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.NewsSearchActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNewsSearchViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNewsTypeListViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsTextViewHolder;
import com.gh.gamecenter.databinding.GameNewsSearchItemBinding;
import com.gh.gamecenter.databinding.GameNewsTypeItemBinding;
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 com.lightgame.utils.Utils;

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

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * Created by LGT on 2016/8/29.
 */
public class GameNewsAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private RecyclerView mGameNewsList;

    private LinearLayout mNoDataLl;

    private ArrayList<NewsEntity> mNewsList;
    private List<String> mTypeList;

    private String mGameId;
    private String mNewsType;
    private String mEntrance;

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

    private int mPage;

    public GameNewsAdapter(Context context, List<String> tList, RecyclerView mGameNewsList, String id, String type,
                           String entrance, LinearLayout noDataLl) {
        super(context);

        this.mGameNewsList = mGameNewsList;
        this.mNoDataLl = noDataLl;

        mNewsList = new ArrayList<>();
        mTypeList = tList;

        mGameId = id;
        mNewsType = type;
        mEntrance = entrance;

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

        addList();
    }

    public void addList() {
        if (isLoading) {
            return;
        }
        isLoading = true;
        notifyItemChanged(getItemCount() - 1);

        Observable<List<NewsEntity>> observable;
        if (mContext.getString(R.string.news_all).equals(mNewsType)) {
            observable = RetrofitManager.getInstance().getApi().getGameNews(
                    UrlFilterUtils.getFilterQuery("game_id", mGameId), 20, mPage);
        } else {
            observable = RetrofitManager.getInstance().getApi().getGameNews(
                    UrlFilterUtils.getFilterQuery("game_id", mGameId, "type", mNewsType), 20, mPage);
        }
        observable.subscribeOn(Schedulers.io())
                .map(new Function<List<NewsEntity>, List<NewsEntity>>() {
                    @Override
                    public List<NewsEntity> apply(List<NewsEntity> list) {
                        // 去除重复数据
                        Config.filterPluginArticle(list);
                        return NewsUtils.removeDuplicateData(mNewsList, list);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<NewsEntity>>() {
                    @Override
                    public void onResponse(List<NewsEntity> response) {
                        if (mPage == 1) {
                            mNewsList.clear();
                        }

                        if (response.size() != 0) {
                            mNewsList.addAll(response);
                            notifyItemRangeInserted(mNewsList.size() - response.size() + 2, response.size());
                            notifyItemChanged(getItemCount() - response.size() - 2);
                            if (response.size() < 20) {
                                isRemove = true;
                                notifyItemChanged(getItemCount() - 1);
                            }
                        } else {
                            isRemove = true;
                            notifyItemChanged(getItemCount() - 1);
                        }

                        if (mPage == 1) {
                            mGameNewsList.scrollToPosition(1);
                            if (mNewsList.size() == 0) {
                                mNoDataLl.setVisibility(View.VISIBLE);
                                mGameNewsList.setVisibility(View.GONE);

                            } else {
                                mNoDataLl.setVisibility(View.GONE);
                                mGameNewsList.setVisibility(View.VISIBLE);
                            }
                        }

                        mPage++;
                        isLoading = false;
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        isLoading = false;
                        isNetworkError = true;
                        notifyItemChanged(getItemCount() - 1);
                    }
                });
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 0) {
            return new GameNewsSearchViewHolder(GameNewsSearchItemBinding.inflate(mLayoutInflater, parent, false));
        } else if (viewType == 1) {
            return new GameNewsTypeListViewHolder(GameNewsTypeItemBinding.inflate(mLayoutInflater, parent, false));
        } else if (mNewsList.size() > 0 && viewType > 1 && viewType <= 1 + mNewsList.size()) {
            return new NewsTextViewHolder(NewsTextItemBinding.inflate(mLayoutInflater, parent, false));
        } else {
            View view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof GameNewsTypeListViewHolder) {
            GameNewsTypeListViewHolder viewHolder = (GameNewsTypeListViewHolder) holder;
            ViewGroup.LayoutParams params = viewHolder.binding.gameNewsTypeList.getLayoutParams();
            params.height = (int) Math.ceil(mTypeList.size() / 5f) * DisplayUtils.dip2px(mContext, 35) + DisplayUtils.dip2px(mContext, 12);
            viewHolder.binding.gameNewsTypeList.setLayoutParams(params);

            if (viewHolder.binding.gameNewsTypeList.getAdapter() == null) {
                viewHolder.binding.gameNewsTypeList.setHasFixedSize(true);
                viewHolder.binding.gameNewsTypeList.setLayoutManager(new GridLayoutManager(mContext, 5));
                viewHolder.binding.gameNewsTypeList.setAdapter(new GameNewsTypeListAdapter(mContext, mTypeList, mNewsType));
            }
        } else if (holder instanceof NewsTextViewHolder) {
            final NewsTextViewHolder viewHolder = (NewsTextViewHolder) holder;

            viewHolder.binding.newsTextType.setVisibility(View.GONE);

            // 第一个
            if (position - 2 == 0) {
                viewHolder.binding.newsTextLine.setVisibility(View.GONE);
            } else {
                viewHolder.binding.newsTextLine.setVisibility(View.VISIBLE);
            }


            final NewsEntity newsEntity = mNewsList.get(position - 2);
            viewHolder.binding.newsTextType.setBackgroundResource(NewsUtils.getDrawableIdByType(newsEntity.getType()));
            viewHolder.binding.newsTextType.setText(newsEntity.getType());
            viewHolder.binding.newsTextTitle.setText(Html.fromHtml(newsEntity.getTitle()));
            viewHolder.binding.getRoot().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DataCollectionUtils.uploadClick(mContext, mNewsType, "游戏新闻列表", newsEntity.getTitle());

                    // 统计阅读量
                    NewsUtils.statNewsViews(newsEntity.getId());
                    NewsDetailActivity.startNewsDetailActivity(mContext, newsEntity,
                            StringUtils.buildString(mEntrance, "+(游戏新闻列表[", mNewsType + "])"));
                }
            });
        } else if (holder instanceof FooterViewHolder) {
            FooterViewHolder viewHolder = ((FooterViewHolder) holder);
            viewHolder.initItemPadding();
            viewHolder.initFooterViewHolder(isLoading, isNetworkError, isRemove, v -> {
                if (isNetworkError) {
                    isNetworkError = false;
                    notifyItemChanged(getItemCount() - 1);
                    addList();
                }
            });
        } else if (holder instanceof GameNewsSearchViewHolder) {
            if (isOpenKeyBoard) {
                ((GameNewsSearchViewHolder) holder).binding.gameNewsEtSearch.requestFocus();
                InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                isOpenKeyBoard = false;
            }

            GameNewsSearchViewHolder searchViewHolder = ((GameNewsSearchViewHolder) holder);
            searchViewHolder.binding.gameNewsTvSearch.setOnClickListener(v -> {
                String searchKey = ((GameNewsSearchViewHolder) holder).binding.gameNewsEtSearch.getText().toString().trim();
                if (searchKey.length() >= 1) {
                    Intent intent = NewsSearchActivity.getIntent(mContext, "搜索结果", searchKey, mGameId,
                            StringUtils.buildString(mEntrance, "+(游戏新闻列表[", mNewsType, "])"));
                    mContext.startActivity(intent);
                } else {
                    Utils.toast(mContext, R.string.search_hint);
                }
            });

            TextHelper.limitTheLengthOfEditText(searchViewHolder.binding.gameNewsEtSearch, 50, () -> Utils.toast(searchViewHolder.binding.gameNewsEtSearch.getContext(), "最多输入50个字"));
        }
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

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

    public ArrayList<NewsEntity> getNewsList() {
        return mNewsList;
    }

    public boolean isLoading() {
        return isLoading;
    }

    public boolean isRemove() {
        return isRemove;
    }

    public boolean isNetworkError() {
        return isNetworkError;
    }

    public void openKeyBoard() {
        isOpenKeyBoard = true;
        notifyItemChanged(0);
    }

}
