package com.halo.assistant.fragment.myconcern;

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

import androidx.core.content.ContextCompat;

import com.gh.common.util.NewFlatLogUtils;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.common.databind.BindingAdapters;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.gamecenter.feature.databinding.ConcernItemBinding;
import com.gh.gamecenter.feature.utils.ApkActiveUtils;
import com.gh.gamecenter.feature.utils.ConcernUtils;
import com.gh.common.util.DataCollectionUtils;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.feature.viewholder.ConcernViewHolder;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.login.user.UserManager;
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.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * Created by LGT on 2016/9/20.
 */
class MyConcernAdapter extends BaseRecyclerAdapter<ConcernViewHolder> {

    private OnRequestCallBackListener mListener;

    private List<GameEntity> mConcernGameList;

    private String mEntrance;

    MyConcernAdapter(Context context, OnRequestCallBackListener listener, String entrance) {
        super(context);
        mListener = listener;
        mEntrance = entrance;
        mConcernGameList = new ArrayList<>();

        initConcernGame();
    }

    public void initConcernGame() {
        mConcernGameList.clear();

        if (TextUtils.isEmpty(UserManager.getInstance().getToken())) {
            mListener.loadDone(null);
            return;
        }

        RetrofitManager.getInstance().getApi()
                .getConcern(UserManager.getInstance().getUserId())
                .map(RegionSettingHelper.filterGame)
                .map(ApkActiveUtils.filterMapperList)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<GameEntity>>() {
                    @Override
                    public void onResponse(List<GameEntity> response) {
                        super.onResponse(response);
                        mConcernGameList.addAll(response);
                        notifyDataSetChanged();
                        mListener.loadDone(response);
                        if (response.size() == 0) {
                            mListener.loadEmpty();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        super.onFailure(e);
                        mListener.loadError();
                    }
                });
    }


    @Override
    public ConcernViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ConcernViewHolder(ConcernItemBinding.inflate(mLayoutInflater, parent, false));
    }

    @Override
    public void onBindViewHolder(final ConcernViewHolder holder, int position) {
        final GameEntity gameEntity = mConcernGameList.get(position);

        if (position == getItemCount() - 1) {
            holder.itemView.setPadding(
                    0, DisplayUtils.dip2px(16F),
                    0, DisplayUtils.dip2px(16F));
        }

        BindingAdapters.setGame(holder.binding.concernItemIcon, gameEntity);

        holder.binding.getRoot().setBackground(ContextCompat.getDrawable(mContext, com.gh.gamecenter.common.R.drawable.reuse_listview_item_style));
        holder.binding.concernItemName.setText(gameEntity.getName());
        holder.binding.concernItemName.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_primary));
        if (gameEntity.isRelated()) {
            holder.binding.concernItemConcern.setText("关联关注");
            holder.binding.concernItemConcern.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_tertiary));
            holder.binding.concernItemConcern.setBackground(ContextCompat.getDrawable(mContext, com.gh.gamecenter.feature.R.drawable.button_round_border_eeeeee));
        } else {
            holder.binding.concernItemConcern.setText(R.string.cancel_concern);
            holder.binding.concernItemConcern.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
            holder.binding.concernItemConcern.setBackground(ContextCompat.getDrawable(mContext, R.drawable.button_border_blue_oval));
        }
        holder.binding.concernItemConcern.setOnClickListener(v -> {
            holder.binding.concernItemConcern.setClickable(false);
            holder.itemView.setClickable(false);
            // 删除关注表中的数据，并更新界面

            if (gameEntity.isRelated()) {
                holder.binding.concernItemConcern.setClickable(true);
                holder.itemView.setClickable(true);
            } else {
                NewFlatLogUtils.logGameActivityConcern("game_activity_unsubscribe", gameEntity.getId(), gameEntity.getName());
                ConcernUtils.INSTANCE.deleteConcernData(
                        gameEntity.getId(),
                        new ConcernUtils.OnConcernListener() {
                            @Override
                            public void onSuccess() {
                                // 更新界面->cancelConcern()
                                cancelConcern(gameEntity.getId());

                                DataCollectionUtils.uploadConcern(mContext,
                                        gameEntity.getName(),
                                        gameEntity.getId(),
                                        mContext.getString(R.string.cancel_concern));
                            }

                            @Override
                            public void onError() {
                                Utils.toast(mContext, R.string.concern_cancel_failure);
                                holder.binding.concernItemConcern.setClickable(true);
                                holder.itemView.setClickable(true);
                            }
                        });
            }

        });
        holder.itemView.setOnClickListener(v -> {
            if (mConcernGameList != null && mConcernGameList.size() != 0) {
                GameEntity gameEntity1 = mConcernGameList.get(holder.getPosition());

                DataCollectionUtils.uploadClick(mContext, "列表", "我的关注", gameEntity1.getName());

                GameDetailActivity.startGameDetailActivity(mContext, gameEntity1, StringUtils.buildString(mEntrance, "+(我的关注-列表)"), null);

                NewFlatLogUtils.logGameActivityConcern("game_activity_game_detail", gameEntity1.getId(), gameEntity1.getName());
            }
        });
    }

    @Override
    public int getItemCount() {
        if (mConcernGameList == null) {
            return 0;
        }
        return mConcernGameList.size();
    }

    public List<GameEntity> getConcernGameList() {
        return mConcernGameList;
    }

    public GameEntity cancelConcern(String gameId) {
        for (int i = 0; i < mConcernGameList.size(); i++) {
            GameEntity gameEntity = mConcernGameList.get(i);
            if (gameId.equals(gameEntity.getId())) {

                // 删除关联游戏
                boolean isExitRelate = false;
                for (int j = i + 1; j < mConcernGameList.size(); j++) {
                    GameEntity entity = mConcernGameList.get(j);
                    if (entity.isRelated()) {
                        mConcernGameList.remove(j);
                        j--;
                        isExitRelate = true;
                    } else {
                        break;
                    }
                }

                mConcernGameList.remove(i);
                if (isExitRelate) {
                    notifyDataSetChanged();
                } else {
                    notifyItemRemoved(i);
                }
                if (mConcernGameList.size() == 0) mListener.loadEmpty();
                return gameEntity;
            }
        }
        return null;
    }
}
