package com.gh.gamecenter.adapter;

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

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

import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.CommentUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DirectUtils;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.common.utils.TextHelper;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.CommentViewHolder;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.entity.ArticleCommentParent;
import com.gh.gamecenter.entity.CommentEntity;
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.io.IOException;
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/3/22.
 */
public class CommentDetailAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private OnCommentCallBackListener mOnCommentCallBackListener;

    private List<CommentEntity> mCommentList;

    private RecyclerView mRecyclerView;
    private View mDoDataView;
    private View mDataExceptionView;

    private String mCommentId;

    private boolean mIsOver;
    private boolean mIsLoading;
    private boolean mIsNetworkError;

    private int mPage;

    public CommentDetailAdapter(Context context, String commentId,
                                OnCommentCallBackListener commentCallBackListener,
                                View noDataView, View dataExceptionView, RecyclerView recyclerView) {
        super(context);
        mCommentId = commentId;
        mOnCommentCallBackListener = commentCallBackListener;
        mCommentList = new ArrayList<>();
        mPage = 1;

        mDoDataView = noDataView;
        mDataExceptionView = dataExceptionView;
        mRecyclerView = recyclerView;

        loadData();
    }

    public void loadData() {
        if (mIsLoading) return;
        mIsLoading = true;
        RetrofitManager.getInstance().getApi()
                .getCommentTrace(mCommentId, mPage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<CommentEntity>>() {
                    @Override
                    public void onResponse(List<CommentEntity> response) {
                        super.onResponse(response);
                        mCommentList.addAll(response);

                        if (response.size() < 20) {
                            mIsOver = true;
                        }
                        mDoDataView.setVisibility(View.GONE);
                        mDataExceptionView.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);
                        notifyItemRangeChanged(0, getItemCount() - 1);
                        mPage++;
                        mIsLoading = false;
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        super.onFailure(e);
                        try {
                            if (e != null && e.code() == 404 && e.response().errorBody().string().length() > 0) {
                                mDataExceptionView.setVisibility(View.VISIBLE);
                                mDoDataView.setVisibility(View.GONE);
                                mRecyclerView.setVisibility(View.GONE);
                                Utils.toast(mContext, R.string.content_delete_toast);
                            } else {
                                Utils.toast(mContext, R.string.comment_failure_hint);
                                mIsNetworkError = true;
                                mIsLoading = false;
                                notifyItemChanged(getItemCount() - 1);
                            }
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }

                    }
                });
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ItemViewType.LOADING) {
            View view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        } else {
            View view = mLayoutInflater.inflate(R.layout.comment_item, parent, false);
            return new CommentViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof CommentViewHolder) {
            initCommentViewHolder((CommentViewHolder) holder, position);
        } else if (holder instanceof FooterViewHolder) {
            initFooterViewHolder((FooterViewHolder) holder);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return ItemViewType.LOADING;
        }

        return 100;
    }

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

    private void initCommentViewHolder(final CommentViewHolder holder, int position) {
        final CommentEntity commentEntity = mCommentList.get(position);

        CommentUtils.setCommentUserView(mContext, holder, commentEntity);

        CommentUtils.setCommentTime(holder.commentTimeTv, commentEntity.getTime());
        if (commentEntity.getSource() != null && !commentEntity.getSource().getRegion().isEmpty()) {
            holder.commentTimeTv.setText(holder.commentTimeTv.getText() + " · " + commentEntity.getSource().getRegion());
        }

        TextHelper.highlightTextThatIsWrappedInsideWrapperByDefault(holder.commentContentTv, commentEntity.getContent());
        ArticleCommentParent parent = commentEntity.getParent();
        if (parent != null && !TextUtils.isEmpty(parent.getUser().getName())) {
            holder.quoteContainer.setVisibility(View.VISIBLE);
            holder.quoteAuthorTv.setText(String.format("@%s", parent.getUser().getName()));
            if (parent.getUser().getBadge() != null) {
                holder.quoteAuthorBadgeSdv.setVisibility(View.VISIBLE);
                ImageUtils.display(holder.quoteAuthorBadgeSdv, parent.getUser().getBadge().getIcon());
            } else {
                holder.quoteAuthorBadgeSdv.setVisibility(View.GONE);
            }
            String content;
            if (parent.getActive()) {
                content = parent.getComment();
                holder.quoteContentTv.setTextColor(mContext.getResources().getColor(R.color.text_5d5d5d));
            } else {
                content = mContext.getString(R.string.comment_hide_hint);
                holder.quoteContentTv.setTextColor(mContext.getResources().getColor(R.color.text_d5d5d5));
            }
            TextHelper.highlightTextThatIsWrappedInsideWrapperByDefault(holder.quoteContentTv, content);
        } else {
            holder.quoteContainer.setVisibility(View.GONE);
        }

        holder.commentLikeContainer.setOnClickListener(v -> CheckLoginUtils.checkLogin(mContext,
                "资讯文章-评论-点赞", () ->
                        CommentUtils.postVote(mContext,
                                commentEntity, holder.commentLikeCountTv,
                                holder.commentLikeIv, null)));

        holder.itemView.setOnClickListener(v -> {
            if (holder.commentReply.getVisibility() == View.VISIBLE) {
                CheckLoginUtils.checkLogin(mContext, "资讯文章-评论-回复", () -> {
                    mOnCommentCallBackListener.onCommentCallback(commentEntity);
                });
            }
        });

        holder.commentMore.setOnClickListener(v ->
                CommentUtils.showReportDialog(commentEntity,
                        mContext, false, "资讯文章-评论"));

        holder.commentUserIconDv.setOnClickListener(v -> DirectUtils.directToHomeActivity(mContext, commentEntity.getUser().getId(), "", "文章-评论详情"));
        holder.commentUserNameTv.setOnClickListener(v -> DirectUtils.directToHomeActivity(mContext, commentEntity.getUser().getId(), "", "文章-评论详情"));
        holder.userBadgeSdv.setOnClickListener(v -> {
            DialogUtils.showViewBadgeDialog(mContext, commentEntity.getUser().getBadge(),
                    () -> {
                        MtaHelper.onEvent("进入徽章墙_用户记录", "资讯文章-查看对话", commentEntity.getUser().getName() + "（" + commentEntity.getUser().getId() + "）");
                        MtaHelper.onEvent("徽章中心", "进入徽章中心", "资讯文章-查看对话");
                        DirectUtils.directToBadgeWall(mContext, commentEntity.getUser().getId(), commentEntity.getUser().getName(), commentEntity.getUser().getIcon());
                    });
        });
        holder.badgeNameTv.setOnClickListener(v -> holder.userBadgeSdv.performClick());
        holder.quoteAuthorBadgeSdv.setOnClickListener(v -> {
            DialogUtils.showViewBadgeDialog(mContext, parent.getUser().getBadge(),
                    () -> {
                        MtaHelper.onEvent("进入徽章墙_用户记录", "资讯文章-查看对话", parent.getUser().getName() + "（" + parent.getUser().getId() + "）");
                        MtaHelper.onEvent("徽章中心", "进入徽章中心", "资讯文章-查看对话");
                        DirectUtils.directToBadgeWall(mContext, parent.getUser().getId(), parent.getUser().getName(), parent.getUser().getIcon());
                    });
        });
        if (commentEntity.getPriority() != 0) {
            holder.commentBadge.setVisibility(View.VISIBLE);
        } else {
            holder.commentBadge.setVisibility(View.GONE);
        }
    }

    private void initFooterViewHolder(FooterViewHolder holder) {
        if (mIsNetworkError) {
            holder.getLoading().setVisibility(View.GONE);
            holder.getHint().setText(R.string.loading_error_network);
        } else if (!mIsOver) {
            holder.getHint().setText(R.string.loading);
            holder.getLoading().setVisibility(View.VISIBLE);
        } else if (mCommentList.size() == 0) {
            holder.getLoading().setVisibility(View.GONE);
            holder.getHint().setText(R.string.comment_empty);
        } else {
            holder.getHint().setText(R.string.comment_nomore);
            holder.getLoading().setVisibility(View.GONE);
        }

    }

    public boolean isOver() {
        return mIsOver;
    }

    public boolean isLoading() {
        return mIsLoading;
    }
}
