package com.halo.assistant.fragment.game;

import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.RecyclerView;

import com.gh.common.databind.BindingAdapters;
import com.gh.common.util.DataCollectionUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DownloadItemUtils;
import com.gh.common.util.HomePluggableHelper;
import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.GameViewHolder;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.databinding.GamePluggableItemBinding;
import com.gh.gamecenter.databinding.HomeDividerItemBinding;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.PluginLocation;
import com.gh.gamecenter.feature.game.GameItemViewHolder;
import com.gh.gamecenter.home.HomeDividerViewHolder;
import com.gh.gamecenter.home.HomeFragmentAdapter;
import com.gh.gamecenter.home.PluginDisplayStatus;
import com.gh.gamecenter.packagehelper.PackageRepository;
import com.lightgame.adapter.BaseRecyclerAdapter;
import com.lightgame.download.DownloadEntity;
import com.lightgame.utils.Utils;

import java.util.List;

/**
 * Created by khy on 15/08/17.
 * <p>
 * update on 27/12/19
 * link:https://gitlab.ghzs.com/pm/halo-app-issues/issues/730 (5)
 */

public class GamePluginAdapter extends BaseRecyclerAdapter {
    private List<GameEntity> mPluginList;

    private PluginDisplayStatus mPluginDisplayStatus = PluginDisplayStatus.CLOSE;

    private IUpdateDisplayType mUpdateDisplayType;

    public GamePluginAdapter(Context context, List<GameEntity> pluginList, IUpdateDisplayType updateDisplayType) {
        super(context);
        mPluginList = pluginList;
        mUpdateDisplayType = updateDisplayType;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ItemViewType.ITEM_BODY) {
            View view = mLayoutInflater.inflate(R.layout.game_pluggable_item, parent, false);
            return new GamePluggableViewHolder(GamePluggableItemBinding.bind(view));
        } else {
            View view = mLayoutInflater.inflate(R.layout.home_divider_item, parent, false);
            return new HomeDividerViewHolder(HomeDividerItemBinding.bind(view));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof GamePluggableViewHolder) {
            initGameNormalViewHolder((GamePluggableViewHolder) holder, position);
        } else if (holder instanceof HomeDividerViewHolder) {
            ((HomeDividerViewHolder) holder).bindView(8F);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (mPluginDisplayStatus != PluginDisplayStatus.OPEN) {
            return ItemViewType.ITEM_BODY;
        } else {
            if (position != getItemCount() - 1) {
                return ItemViewType.ITEM_BODY;
            } else {
                return HomeFragmentAdapter.DIVIDER_ITEM;
            }
        }
    }

    private void initGameNormalViewHolder(GamePluggableViewHolder holder, int position) {
        int paddingTop = DisplayUtils.dip2px(8F);
        int paddingBottom = DisplayUtils.dip2px(8F);
        if (position == 0) {
            paddingTop = 0;
        }
        if (position == getItemCount() - 1) {
            paddingBottom = DisplayUtils.dip2px(8F);
        }

        holder.getBinding().gameItemIncluded.getRoot().setPadding(
                DisplayUtils.dip2px(16F), paddingTop,
                DisplayUtils.dip2px(20F), paddingBottom);

        final GameEntity gameEntity = mPluginList.get(position);
        holder.initServerType(gameEntity);
        GamePluggableItemBinding binding = holder.getBinding();
        binding.gameItemIncluded.gameIconView.displayGameIcon(gameEntity);
        BindingAdapters.setGameName(binding.gameItemIncluded.gameName, gameEntity, true, null);
        BindingAdapters.setTextSize(binding.gameItemIncluded.gameRating, gameEntity.getCommentCount() > 3 ? 12 : 10);
        BindingAdapters.setGameTags(binding.gameItemIncluded.labelList, gameEntity);
        ExtensionsKt.setDrawableStart(binding.gameItemIncluded.gameRating, gameEntity.getCommentCount() > 3 ? ExtensionsKt.toDrawable(R.drawable.game_horizontal_rating) : null, null, null);
        binding.gameItemIncluded.gameRating.setPadding(0, 0, gameEntity.getCommentCount() > 3 ? DisplayUtils.dip2px(8) : 0, 0);
        binding.gameItemIncluded.gameRating.setText(gameEntity.getCommentCount() > 3 ? (gameEntity.getStar() == 10.0 ? "10" : String.valueOf(gameEntity.getStar())) : "");
        binding.gameItemIncluded.gameRating.setTextColor(gameEntity.getCommentCount() > 3 ? ExtensionsKt.toColor(R.color.theme_font) : ExtensionsKt.toColor(R.color.theme));
        binding.gameItemIncluded.gameDes.setText(gameEntity.getDecoratedDes());
        binding.gameItemIncluded.recommendStar.setRating(gameEntity.getRecommendStar());
        GameItemViewHolder.initGameSubtitleAndAdLabel(gameEntity, binding.gameItemIncluded.gameSubtitleTv, binding.gameItemIncluded.gameNameContainer, binding.gameItemIncluded.gameName, false, null, false, null);

        holder.itemView.setOnClickListener(v -> {
            MtaHelper.onEvent("首页_新", "点击", "插件化" + (position + 1) + "_" + gameEntity.getName());
            DataCollectionUtils.uploadClick(mContext, "插件化" + "-列表", "游戏-专题", gameEntity.getName());

            GameDetailActivity.startGameDetailActivity(mContext, gameEntity.getId(),
                    StringUtils.buildString("(游戏-专题:插件化-列表[", String.valueOf(1), "])"), gameEntity.getExposureEvent());
        });

        DownloadItemUtils.setOnClickListener(mContext, binding.gameItemIncluded.downloadBtn, gameEntity, 1,
                GamePluginAdapter.this,
                StringUtils.buildString("(游戏-专题:", "插件化", "-列表[", String.valueOf(1), "])"),
                StringUtils.buildString("游戏-专题-", "插件化", ":", gameEntity.getName()), gameEntity.getExposureEvent(),
                () -> MtaHelper.onEvent("首页_新", "点击", "插件化" + (position + 1) + "_" + gameEntity.getName() + "_" + binding.gameItemIncluded.downloadBtn.getText().toString()));
        DownloadItemUtils.updateItem(mContext, gameEntity, new GameViewHolder(holder.getBinding().gameItemIncluded), !gameEntity.isPluggable(), PluginLocation.only_index, false, null);

        holder.getBinding().neverRemind.setOnClickListener(v -> DialogUtils.showPluggableNeverRemindDialog(mContext,
                String.format("%s - %s",
                        gameEntity.getName(),
                        PlatformUtils.getInstance(mContext).getPlatformName(gameEntity.getApk().get(0).getPlatform())),
                () -> {
                    Utils.toast(mContext, "不再提醒设置成功");

                    HomePluggableHelper.setHomePluggableFilterData(gameEntity, true);

                    PackageRepository.INSTANCE.getGameUpdateLiveData().postValue(PackageRepository.INSTANCE.getGameUpdate());

                    mUpdateDisplayType.update(PluginDisplayStatus.DEFAULT);
                }));

        ViewGroup.LayoutParams layoutParams = holder.getBinding().gameItemIncluded.downloadBtn.getLayoutParams();
        if (layoutParams instanceof LinearLayout.LayoutParams) {
            ((LinearLayout.LayoutParams) layoutParams).gravity = Gravity.TOP;
            ((LinearLayout.LayoutParams) layoutParams).topMargin = DisplayUtils.dip2px(4);
        }

        HomePluggableHelper.setHomePluggableFilterData(gameEntity, false);
    }

    @Override
    public int getItemCount() {
        if (mPluginDisplayStatus == PluginDisplayStatus.OPEN) {
            return mPluginList.size() + 1; // 显示底部线条
        } else if (mPluginDisplayStatus == PluginDisplayStatus.OPEN_AND_BUTTON) {
            return mPluginList.size();
        } else if (mPluginDisplayStatus == PluginDisplayStatus.OPEN_TWO_AND_BUTTON) {
            return mPluginList.size() > 2 ? 2 : mPluginList.size();
        } else {
            return 0;
        }
    }

    public void notifyItemByDownload(DownloadEntity downloadEntity) {
        for (int position = 0; position < mPluginList.size(); position++) {
            GameEntity pluginEntity = mPluginList.get(position);
            if (downloadEntity.getName().equals(pluginEntity.getName())) {
                notifyItemChanged(position);
            }
        }
    }

    public void checkResetData(List<GameEntity> pluginList) {
        if (mPluginList != pluginList) {
            mPluginList = pluginList;
            notifyDataSetChanged();
        }
    }

    public void openList(PluginDisplayStatus pluginDisplayStatus) {
        if (mPluginDisplayStatus != pluginDisplayStatus) {
            mPluginDisplayStatus = pluginDisplayStatus;
            notifyDataSetChanged();
        } else {
            notifyItemRangeChanged(0, getItemCount());
        }
    }

    public interface IUpdateDisplayType {
        void update(PluginDisplayStatus status);
    }
}
