package com.halo.assistant.fragment.game;

import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gh.common.constant.Config;
import com.gh.common.util.DataCollectionUtils;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.EnvHelper;
import com.gh.common.util.NewsUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.common.view.VerticalItemDecoration;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsTextViewHolder;
import com.gh.gamecenter.databinding.NewsTextItemBinding;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.utils.Util_System_Keyboard;

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

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

/**
 * Created by CsHeng on 14/12/2017.
 * 游戏新闻搜索结果界面
 */
public class GameNewsSearchResultFragment extends ToolbarFragment {

    private LinearLayout mNoneData;
    private EditText mNewsSearchEt;
    private LinearLayout mLoading;
    private LinearLayout mNoConn;

    private LinearLayoutManager mLayoutManager;
    private List<NewsEntity> mNewsEntities;
    private NewsSearchAdapter mNewsSearchAdapter;

    private boolean mIsLoadOver = true;
    private boolean mIsRemove = false;
    private boolean mIsNetworkError = false;

    private String mSearchKey;
    private String mGameId;

    private final Handler mHandler = new Handler();

    private int mPage = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_game_news_search_result;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        RecyclerView newsSearchRv = view.findViewById(R.id.gamedetail_news_rv);
        TextView newsSearchTv = view.findViewById(R.id.tv_search);
        mNoneData = view.findViewById(R.id.reuse_none_data);
        mNewsSearchEt = view.findViewById(R.id.et_search);
        mLoading = view.findViewById(R.id.gamedetail_news_ll_loading);
        mNoConn = view.findViewById(R.id.reuse_no_connection);

        Bundle args = getArguments();

        String gameName = args.getString(EntranceConsts.KEY_GAMENAME);
        mSearchKey = args.getString(EntranceConsts.KEY_SEARCHKEY);
        mGameId = args.getString(EntranceConsts.KEY_GAMEID);

        setNavigationTitle(gameName);

        mNewsEntities = new ArrayList<>();
        mNewsSearchAdapter = new NewsSearchAdapter();

        mLayoutManager = new LinearLayoutManager(getContext());

        newsSearchRv.setLayoutManager(mLayoutManager);
        newsSearchRv.setAdapter(mNewsSearchAdapter);
        newsSearchRv.addItemDecoration(new VerticalItemDecoration(getContext(), false));

        mNewsSearchEt.setText(mSearchKey);
        mNewsSearchEt.setSelection(mSearchKey.length());

        loadNewsData(mPage);

        newsSearchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchKey = mNewsSearchEt.getText().toString().trim();
                if (mSearchKey.length() >= 1) {
                    mNewsEntities.clear();
                    mNewsSearchAdapter.notifyDataSetChanged();
                    mLoading.setVisibility(View.VISIBLE);
                    mNoneData.setVisibility(View.GONE);

                    Util_System_Keyboard.hideSoftKeyboard(getActivity());

                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mPage = 1;
                            loadNewsData(mPage);
                        }
                    }, 500);

                } else {
                    toast(R.string.search_hint);
                }

            }
        });

        newsSearchRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLayoutManager.findLastVisibleItemPosition() + 1 == mNewsSearchAdapter.getItemCount()
                        && mIsLoadOver && !mIsRemove && !mIsNetworkError) {
                    mIsLoadOver = false;
                    mPage++;
                    loadNewsData(mPage);
                }
            }
        });

        mNoConn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNoConn.setVisibility(View.GONE);
                mLoading.setVisibility(View.VISIBLE);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadNewsData(1);
                    }
                }, 1000);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    private void loadNewsData(final int page) {
        RetrofitManager.getInstance().getApi()
                .getSearchNews(EnvHelper.getHost() + "articles:search?keyword=" + mSearchKey + "&view=digest&filter="
                        + UrlFilterUtils.getFilterQuery("game_id", mGameId) + "&page=" + mPage)
                .map(list -> {
                    Config.filterPluginArticle(list);
                    // 去掉重复数据
                    return NewsUtils.removeDuplicateData(mNewsEntities, list);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<NewsEntity>>() {
                    @Override
                    public void onResponse(List<NewsEntity> response) {
                        mIsLoadOver = true;
                        mLoading.setVisibility(View.GONE);
                        mNoneData.setVisibility(View.GONE);

                        if (response.size() != 0) {
                            mNewsEntities.addAll(response);
                            mNewsSearchAdapter.notifyDataSetChanged();
                        } else {
                            if (page == 1) {
                                mNoneData.setVisibility(View.VISIBLE);
                            }

                            mIsRemove = true;
                            mNewsSearchAdapter.notifyItemChanged(mNewsSearchAdapter.getItemCount() - 1);
                        }

                        if (response.size() < 20) {
                            mIsRemove = true;
                        }
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        if (page == 1) {
                            mNoConn.setVisibility(View.VISIBLE);
                            mLoading.setVisibility(View.GONE);
                        }
                        mIsLoadOver = true;
                        toast(R.string.loading_failed_hint);
                        mIsNetworkError = true;
                        mNewsSearchAdapter.notifyItemChanged(mNewsSearchAdapter.getItemCount() - 1);
                    }
                });
    }

    //TODO move out
    public class NewsSearchAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 0) {
                View view = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.refresh_footerview, parent, false);
                return new FooterViewHolder(view);
            } else {
                return new NewsTextViewHolder(NewsTextItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
            }
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof NewsTextViewHolder) {
                NewsTextViewHolder viewHolder = (NewsTextViewHolder) holder;
                viewHolder.binding.newsTextTitle.setText(Html.fromHtml(mNewsEntities.get(position).getTitle()));
                viewHolder.binding.newsTextType.setVisibility(View.GONE);
                viewHolder.binding.newsTextLine.setVisibility(View.GONE);
                viewHolder.binding.getRoot().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        NewsEntity newsEntity = mNewsEntities.get(holder.getPosition());

                        DataCollectionUtils.uploadClick(getContext(),
                                "列表", "游戏新闻搜索", newsEntity.getTitle());

                        // 统计阅读量
                        NewsUtils.statNewsViews(newsEntity.getId());
                        NewsDetailActivity.startNewsDetailActivity(getContext(), newsEntity,
                                mEntrance + "+(游戏新闻搜索[" + mSearchKey + "])");
                    }
                });
            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder viewHolder = (FooterViewHolder) holder;
                if (mIsNetworkError) {
                    viewHolder.getLoading().setVisibility(View.GONE);
                    viewHolder.getHint().setText(R.string.loading_failed_retry);
                    viewHolder.itemView.setClickable(true);
                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mIsNetworkError = false;
                            notifyItemChanged(getItemCount() - 1);
                            loadNewsData(mPage);
                        }
                    });
                } else if (mIsRemove) {
                    viewHolder.getLoading().setVisibility(View.GONE);
                    viewHolder.getHint().setText(R.string.loading_complete);
                    viewHolder.itemView.setClickable(false);
                } else {
                    viewHolder.getLoading().setVisibility(View.VISIBLE);
                    viewHolder.getHint().setText(R.string.loading);
                    viewHolder.itemView.setClickable(false);
                }
            }

        }

        @Override
        public int getItemViewType(int position) {
            if (position == mNewsEntities.size()) {
                return 0;
            } else {
                return 1;
            }
        }

        @Override
        public int getItemCount() {
            if (mNewsEntities.isEmpty()) {
                return 0;
            }
            return mNewsEntities.size() + 1;
        }

    }

}
