package com.halo.assistant.fragment.myconcern;

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

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.gh.common.constant.Config;
import com.gh.common.databind.BindingAdapters;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.gamecenter.feature.utils.ApkActiveUtils;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.ConcernUtils;
import com.gh.common.util.DataCollectionUtils;
import com.gh.common.util.NewFlatLogUtils;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.ConcernViewHolder;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.databinding.ConcernItemBinding;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.entity.GameInstall;
import com.gh.gamecenter.manager.PackagesManager;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.adapter.BaseRecyclerAdapter;
import com.lightgame.utils.Utils;

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

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

/**
 * Created by LGT on 2016/9/20.
 * <p>
 * 我的关注，推荐关注
 */
public class MyConcernRecommendAdapter extends BaseRecyclerAdapter<ConcernViewHolder> {

    private OnRequestCallBackListener mListener;

    private List<GameEntity> mRecommendGameList;
    private List<GameEntity> mConcernGameList;

    private String mEntrance;

    public MyConcernRecommendAdapter(Context context, OnRequestCallBackListener listener, List<GameEntity> concernGame, String entrance) {
        super(context);
        mListener = listener;
        mEntrance = entrance;
        mConcernGameList = concernGame;
        mRecommendGameList = new ArrayList<>();

        init();
    }

    private void init() {
        // 获取已安装游戏的digest
        List<Observable<GameEntity>> sequences = new ArrayList<>();
        HashSet<String> repeatGameSet = new HashSet<>();
        for (GameInstall installInfo : PackagesManager.getFilterSameApkInstalledList()) {
            String gameId = installInfo.getId();
            String packageName = installInfo.getPackageName();
            // 过滤重复 ID 以及设置里关闭下载的那部分特殊包名的包
            if (!repeatGameSet.contains(gameId)
                    && !RegionSettingHelper.shouldThisGameBeFiltered(gameId)
                    && (Config.getSettings() == null
                    || !Config.getSettings().getGameDownloadBlackList().contains(packageName))) {
                sequences.add(RetrofitManager.getInstance().getApi().getGameDigest(gameId));
                repeatGameSet.add(gameId);
            }
        }
        Observable.mergeDelayError(sequences)
                .map(ApkActiveUtils.filterMapper)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<GameEntity>() {
                    @Override
                    public void onComplete() {
                        initRecommendGame();
                    }

                    @Override
                    public void onFailure(@Nullable HttpException e) {
                        initRecommendGame();
                    }

                    @Override
                    public void onNext(GameEntity response) {
                        if (response.isNewsExists()) {
                            ApkActiveUtils.filterHideApk(response);
                            mRecommendGameList.add(response);
                        }
                    }
                });
    }

    private void initRecommendGame() {
        if (mConcernGameList != null) { // 过滤已关注的游戏
            for (int i = 0; i < mRecommendGameList.size(); i++) {
                String recommendId = mRecommendGameList.get(i).getId();
                for (int j = 0; j < mConcernGameList.size(); j++) {
                    String concernId = mConcernGameList.get(j).getId();
                    if (recommendId.equals(concernId)) {
                        mRecommendGameList.remove(i);
                        i--;
                        break;
                    }
                }
            }
        }

        if (mRecommendGameList != null
                && mRecommendGameList.size() != 0
                && mListener != null) {
            mListener.loadDone();
        }
    }

    @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 = mRecommendGameList.get(position);
        BindingAdapters.setGame(holder.binding.concernItemIcon, gameEntity);

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

        holder.binding.concernItemName.setText(gameEntity.getName());
        holder.binding.concernItemConcern.setPadding(
                DisplayUtils.dip2px(12F), DisplayUtils.dip2px(4F),
                DisplayUtils.dip2px(12F), DisplayUtils.dip2px(4F));
        holder.binding.concernItemConcern.setText(R.string.concern);
        holder.binding.concernItemConcern.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.white));
        holder.binding.concernItemConcern.setBackground(ContextCompat.getDrawable(mContext, R.drawable.button_blue_oval));
        holder.binding.concernItemConcern.setOnClickListener(v ->
                CheckLoginUtils.checkLogin(mContext, "我的关注-热门游戏推荐-[关注]", () -> {
                    holder.binding.concernItemConcern.setClickable(false);
                    holder.itemView.setClickable(false);
                    ConcernUtils.INSTANCE.postConcernGameId(gameEntity.getId(), new ConcernUtils.OnConcernListener() {
                        @Override
                        public void onSuccess() {
                            // 更新界面->concernGame()
                            DataCollectionUtils.uploadConcern(mContext,
                                    gameEntity.getName(), gameEntity.getId(), mContext.getString(R.string.concern));

                            Utils.toast(mContext, R.string.concern_success);
                        }

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

                }));
        holder.itemView.setOnClickListener(v -> {
            GameEntity gameEntity1 = mRecommendGameList.get(holder.getPosition());

            DataCollectionUtils.uploadClick(mContext,
                    "推荐",
                    "我的关注",
                    gameEntity1.getName());

            NewFlatLogUtils.logMyGameFollowTabHotGameClick("游戏详情", gameEntity1.getId(), gameEntity1.getName());
            GameDetailActivity.startGameDetailActivity(mContext, gameEntity1, StringUtils.buildString(mEntrance, "+(我的关注-推荐)"), null);
        });
        holder.itemView.setBackground(ContextCompat.getDrawable(holder.itemView.getContext(), R.drawable.reuse_listview_item_style));
        holder.binding.concernItemName.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.text_title));
    }

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

    public List<GameEntity> getRecommendGameList() {
        return mRecommendGameList;
    }

    public GameEntity concernGame(String gameId) {
        for (int i = 0; i < mRecommendGameList.size(); i++) {
            GameEntity gameEntity = mRecommendGameList.get(i);
            if (gameEntity.getId().equals(gameId)) {
                mRecommendGameList.remove(i);
                notifyItemRemoved(i);
                if (mRecommendGameList.size() == 0
                        && mListener != null) {
                    mListener.loadEmpty();
                }
                return gameEntity;
            }
        }
        return null;
    }
}
