package com.gh.gamecenter.adapter;

import static com.gh.common.constant.Config.URL_ARTICLE;
import static com.gh.gamecenter.R.string.loading;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.WebActivity;
import com.gh.gamecenter.adapter.viewholder.ReuseViewHolder;
import com.gh.gamecenter.adapter.viewholder.ToolBoxViewHolder;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.entity.SuggestType;
import com.gh.gamecenter.common.entity.ToolBoxEntity;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.databinding.ToolboxItemBinding;
import com.gh.gamecenter.help.HelpAndFeedbackBridge;
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 24/05/17.
 */

public class ToolBoxRvAdapter extends BaseRecyclerAdapter {

    private OnRequestCallBackListener mCallBackListener;

    private List<ToolBoxEntity> mEntityList;

    private String mSearchKey;

    private boolean mIsSearch;
    private boolean mIsLoading;
    private boolean mIsOver;
    private boolean mIsNetworkError;
    private int mPage;

    public ToolBoxRvAdapter(Context context, OnRequestCallBackListener listener, boolean isSearch, String key) {
        super(context);
        this.mIsSearch = isSearch;
        this.mSearchKey = key;
        mPage = 1;

        mCallBackListener = listener;
        mEntityList = new ArrayList<>();
        loadData();
    }

    public void loadData() {
        if (mIsLoading) {
            return;
        }
        mIsLoading = true;
        RetrofitManager.getInstance().getApi()
                .getToolKitData(mPage, UrlFilterUtils.getFilterQuery("keyword", mIsSearch ? mSearchKey : ""))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<ToolBoxEntity>>() {
                    @Override
                    public void onResponse(List<ToolBoxEntity> response) {
                        super.onResponse(response);
                        if (response.size() > 0) {
                            mEntityList.addAll(response);
                        }
                        mCallBackListener.loadDone();

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

                        notifyDataSetChanged();

                        mPage++;
                        mIsLoading = false;

                        if (mEntityList.size() == 0) {
                            mCallBackListener.loadEmpty();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        super.onFailure(e);
                        mIsLoading = false;
                        if (mEntityList.size() == 0) {
                            mCallBackListener.loadError();
                        } else {
                            mIsNetworkError = true;
                            notifyItemChanged(getItemCount() - 1);
                        }
                    }
                });
    }

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

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 2) {
            View view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        } else if (viewType == 1) {
            View view = mLayoutInflater.inflate(R.layout.toolbox_hint_item, parent, false);
            return new ReuseViewHolder(view);
        } else {
            View view = mLayoutInflater.inflate(R.layout.toolbox_item, parent, false);
            return new ToolBoxViewHolder(ToolboxItemBinding.bind(view));
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ToolBoxViewHolder) {
            ToolBoxViewHolder viewHolder = (ToolBoxViewHolder) holder;
            ToolBoxEntity toolBoxEntity = mEntityList.get(position - 1);
            initToolBoxViewHolder(viewHolder, toolBoxEntity);
        } else if (holder instanceof FooterViewHolder) {
            FooterViewHolder viewHolder = (FooterViewHolder) holder;
            initFooterViewHolder(viewHolder);
        } else if (holder instanceof ReuseViewHolder) {
            holder.itemView.setOnClickListener(v -> {
                MtaHelper.onEvent("我的光环_新", "工具箱", "点击反馈");
                HelpAndFeedbackBridge.startSuggestionActivity(mContext, SuggestType.normal, null, null);
            });
        }
    }

    @Override
    public int getItemCount() {
        if (mEntityList.size() > 0) {
            return mEntityList.size() + 2;
        } else {
            return 0;
        }

    }

    private void initFooterViewHolder(FooterViewHolder viewHolder) {
        viewHolder.initItemPadding();
        if (mIsNetworkError) {
            viewHolder.getLoading().setVisibility(View.GONE);
            viewHolder.getHint().setText(R.string.loading_failed_retry);
            viewHolder.itemView.setClickable(true);
            viewHolder.itemView.setOnClickListener(v -> loadData());
        } else if (mIsOver) {
            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(loading);
            viewHolder.itemView.setClickable(false);
        }
    }

    private void initToolBoxViewHolder(ToolBoxViewHolder viewHolder, final ToolBoxEntity toolBoxEntity) {
        viewHolder.binding.toolboxItemDes.setText(toolBoxEntity.getDes());
        viewHolder.binding.toolboxItemTitle.setText(toolBoxEntity.getName());
        ImageUtils.display(viewHolder.binding.toolboxItemGameThumb, toolBoxEntity.getIcon());

        viewHolder.itemView.setOnClickListener(v -> {
            String url = toolBoxEntity.getUrl();
//                http://www.ghzs666.com/article/59291e7ce9a64a496cfd6897.html
            if (url != null && url.contains(URL_ARTICLE)) {
                String newsId = url.substring(url.lastIndexOf("/") + 1, url.length() - 5); // 5: ".html"
                Intent intent = NewsDetailActivity.getIntentById(mContext, newsId, "工具箱列表");
                mContext.startActivity(intent);
            } else {
                mContext.startActivity(WebActivity.getWebByCollectionTools(mContext, toolBoxEntity, false));
            }
        });
    }

    public boolean isOver() {
        return mIsOver;
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    public boolean isNetworkError() {
        return mIsNetworkError;
    }
}
