package com.gh.common.util;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.gh.common.filter.RegionSetting;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.repository.ReservationRepository;
import com.gh.common.simulator.SimulatorGameManager;
import com.gh.common.xapk.XapkInstaller;
import com.gh.common.xapk.XapkUnzipStatus;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.DetailViewHolder;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.entity.LinkEntity;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.core.utils.SpeedUtils;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.PluginLocation;
import com.gh.gamecenter.feature.view.DownloadButton;
import com.gh.gamecenter.manager.PackagesManager;
import com.gh.vspace.VHelper;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;

import java.util.Objects;

/**
 * Created by khy on 27/06/17.
 * 详情下载工具类
 */
public class DetailDownloadUtils {

    public static void updateViewHolder(DetailViewHolder viewHolder) {
        updateViewHolder(viewHolder, false);
    }

    /**
     * 更新底部下载区域
     *
     * @param viewHolder           下载区域的包裹
     * @param ignoreDownloadEntity 忽略下载实体（往往用于下载异常时）
     */
    public static void updateViewHolder(DetailViewHolder viewHolder, boolean ignoreDownloadEntity) {
        GameEntity gameEntity = viewHolder.getGameEntity();
        String downloadAddWord = gameEntity.getDownloadAddWord();

        // 多版本下载箭头
        if (viewHolder.getMultiVersionDownloadTv() != null) {
            viewHolder.getMultiVersionDownloadTv().setVisibility(View.GONE);
        }

        viewHolder.setSpeedViewsVisible(false);
        // 默认为显示状态
        viewHolder.getDownloadPb().setVisibility(View.VISIBLE);

        // 根据预置的配置更新 ViewHolder 的状态 (譬如青少年模式、下载内容为空等)
        if (updateViewHolderWithPredefinedConfig(viewHolder, gameEntity)) {
            return;
        }

        // 游戏只包含单 APK 的情况
        if (gameEntity.getApk().size() == 1) {
            boolean showVGame = false; // 真下载按钮(DownloadButton)是否需要显示为畅玩，包括单按钮显示和双按钮显示
            boolean showDualDownloadButton = false; // 是否显示双下载按钮

            int gameDownloadMode = gameEntity.getGameDownloadButtonMode(); // 获取游戏的下载按钮模式

            DownloadEntity downloadEntity = null;
            if (!ignoreDownloadEntity) {
                downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(gameEntity);
            }

            // 不支持双下载按钮的情况时（新闻详情、礼包详情页），优选一个下载方式显示
            if (!viewHolder.isSupportDualButton()) {
                boolean performAsVGame = GameUtils.shouldPerformAsVGame(gameEntity);
                if (performAsVGame) {
                    gameDownloadMode = GameEntity.GAME_DOWNLOAD_BUTTON_MODE_VGAME;
                } else {
                    gameDownloadMode = GameEntity.GAME_DOWNLOAD_BUTTON_MODE_DOWNLOAD;
                }
            }

            if (gameDownloadMode == GameEntity.GAME_DOWNLOAD_BUTTON_MODE_DOWNLOAD) {
                showVGame = false;
                if (viewHolder.getLocalDownloadContainer() != null) {
                    viewHolder.getLocalDownloadContainer().setVisibility(View.GONE);
                }
            } else if (gameDownloadMode == GameEntity.GAME_DOWNLOAD_BUTTON_MODE_VGAME) {
                showVGame = true;
                if (viewHolder.getLocalDownloadContainer() != null) {
                    viewHolder.getLocalDownloadContainer().setVisibility(View.GONE);
                }
            } else if (gameDownloadMode == GameEntity.GAME_DOWNLOAD_BUTTON_MODE_DUAL) {
                showVGame = true;
                showDualDownloadButton = true;
                if (viewHolder.getLocalDownloadContainer() != null) {
                    viewHolder.getLocalDownloadContainer().setVisibility(View.VISIBLE);
                }

                // 1.畅玩未安装/当前游戏配置了加速，且当前下载的默认类型为"普通下载"，且用户未安装时，禁用双按钮，禁用畅玩
                if ((!VHelper.isInstalled(gameEntity.getUniquePackageName())
                        && !PackagesManager.isInstalled(gameEntity.getUniquePackageName()) || gameEntity.getCanSpeed())
                        && downloadEntity != null
                        && ExtensionsKt.isLocalDownloadInDualDownloadMode(downloadEntity)
                ) {
                    viewHolder.getDownloadPb().setVisibility(View.GONE);
                    if (viewHolder.getOverlayTv() != null) {
                        viewHolder.getOverlayTv().setVisibility(View.GONE);
                    }
                    // 此时需要将 本地占位按钮样式改成单条样式
                    if (viewHolder.getLocalDownloadContainer() != null) {
                        viewHolder.getLocalDownloadContainer().setBackgroundResource(com.gh.gamecenter.common.R.drawable.bg_common_button_fill_gradient_blue);
                    }
                    if (viewHolder.getLocalDownloadTitleTv() != null) {
                        viewHolder.getLocalDownloadTitleTv().setTextColor(ExtensionsKt.toColor(com.gh.gamecenter.common.R.color.text_aw_primary, viewHolder.getContext()));
                    }
                } else {
                    viewHolder.getDownloadPb().setVisibility(View.VISIBLE);
                    // 将占位按钮样式恢复成左半边样式
                    if (viewHolder.getLocalDownloadContainer() != null) {
                        viewHolder.getLocalDownloadContainer().setBackgroundResource(com.gh.gamecenter.common.R.drawable.bg_common_button_light_fill_blue);
                    }
                    if (viewHolder.getLocalDownloadTitleTv() != null) {
                        viewHolder.getLocalDownloadTitleTv().setTextColor(ExtensionsKt.toColor(com.gh.gamecenter.common.R.color.text_theme, viewHolder.getContext()));
                    }
                }
            }

            if (showDualDownloadButton) {
                // 双下载按钮时更新占位的下载按钮
                updateWithSingleApk(
                        gameEntity,
                        viewHolder,
                        viewHolder.getLocalDownloadButton(),
                        downloadAddWord,
                        false,
                        true,
                        downloadEntity
                );
            }

            // 更新默认的下载按钮
            updateWithSingleApk(
                    gameEntity,
                    viewHolder,
                    viewHolder.getDownloadPb(),
                    downloadAddWord,
                    showVGame,
                    showDualDownloadButton,
                    downloadEntity
            );
            if (downloadEntity != null && downloadEntity.getStatus() != DownloadStatus.done) {
                // 如果存在未完成的任务，则不显示加速按钮
            } else {
                viewHolder.checkIfShowSpeedUi(showVGame, showDualDownloadButton);
            }
        } else {
            // 游戏包含多 APK 的情况
            viewHolder.getMultiVersionDownloadTv().setText("选择下载你的版本" + (TextUtils.isEmpty(downloadAddWord) ? "" : "-" + downloadAddWord));
            viewHolder.getMultiVersionDownloadTv().setVisibility(View.VISIBLE);
            viewHolder.getDownloadPb().setTag(com.gh.gamecenter.feature.R.string.download, viewHolder.getMultiVersionDownloadTv().getText());
            viewHolder.getDownloadPb().setText("");
            viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(gameEntity);
            if (downloadEntity != null) {
                switch (downloadEntity.getStatus()) {
                    case downloading:
                        viewHolder.getDownloadTips().setVisibility(View.VISIBLE);
                        ExtensionsKt.setDownloadTipsAnimation(viewHolder.getDownloadTips(), true);
                        break;
                    case done:
                    case pause:
                    case waiting:
                    case timeout:
                    case subscribe:
                    case neterror:
                    case overflow:
                        viewHolder.getDownloadTips().setVisibility(View.VISIBLE);
                        ExtensionsKt.setDownloadTipsAnimation(viewHolder.getDownloadTips(), false);
                        break;
                    default:
                        viewHolder.getDownloadTips().setVisibility(View.GONE);
                        break;
                }
            } else {
                viewHolder.getDownloadTips().setVisibility(View.GONE);
            }
        }
    }

    /**
     * 更新只有单个 APK 文件时候的下载按钮状态
     *
     * @param downloadButton         下载按钮，可能是真的下载按钮也可能只是占位下载按钮
     * @param downloadAddWord        下载按钮的补充文案
     * @param showAsVGame            是否显示为畅玩游戏
     * @param showDualDownloadButton 是否正显示为双下载按钮
     */

    private static void updateWithSingleApk(GameEntity gameEntity,
                                            DetailViewHolder viewHolder,
                                            DownloadButton downloadButton,
                                            String downloadAddWord,
                                            boolean showAsVGame,
                                            boolean showDualDownloadButton,
                                            DownloadEntity downloadEntity) {
        Context context = viewHolder.getContext();
        TextView overlayTv = viewHolder.getOverlayTv();

        boolean containsAddWord = !TextUtils.isEmpty(downloadAddWord); // 是否存在下载补充文案

        // 根据游戏实体获取下载按钮文案
        String rawBtnText = GameUtils.getDownloadBtnText(context, gameEntity, false, showAsVGame, PluginLocation.only_game);

        if (showAsVGame) {
            // 显示为畅玩游戏
            if (context.getString(com.gh.gamecenter.feature.R.string.launch).equals(rawBtnText)) {
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
            } else {
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            }

            String decoratedBtnText;
            // 双下载按钮时，显示特殊样式
            if (showDualDownloadButton
                    && (context.getString(com.gh.gamecenter.feature.R.string.launch).equals(rawBtnText) || context.getString(com.gh.gamecenter.feature.R.string.install).equals(rawBtnText) || context.getString(com.gh.gamecenter.feature.R.string.smooth).equals(rawBtnText) || context.getString(com.gh.gamecenter.feature.R.string.update).equals(rawBtnText))) {
                if (context.getString(com.gh.gamecenter.feature.R.string.smooth).equals(rawBtnText)) {
                    decoratedBtnText = context.getString(com.gh.gamecenter.feature.R.string.download_v);
                } else if (context.getString(com.gh.gamecenter.feature.R.string.update).equals(rawBtnText)) {
                    decoratedBtnText = context.getString(com.gh.gamecenter.feature.R.string.update_v);
                } else {
                    decoratedBtnText = context.getString(com.gh.gamecenter.feature.R.string.launch_v);
                }

                if (overlayTv != null && downloadButton.getVisibility() != View.GONE) {
                    overlayTv.setVisibility(View.VISIBLE);
                    overlayTv.setText(decoratedBtnText);
                    downloadButton.setText("");
                }
            } else {
                decoratedBtnText = rawBtnText + (containsAddWord ? "" : downloadAddWord) + getWrappedDownloadSizeText(viewHolder);

                if (overlayTv != null && downloadButton.getVisibility() != View.GONE) {
                    if (context.getString(com.gh.gamecenter.feature.R.string.launch).equals(rawBtnText)
                            || context.getString(com.gh.gamecenter.feature.R.string.install).equals(rawBtnText)) {
                        overlayTv.setVisibility(View.VISIBLE);
                        overlayTv.setText("启动（畅玩）");
                    } else {
                        overlayTv.setVisibility(View.GONE);
                        downloadButton.setText(decoratedBtnText);
                    }
                } else {
                    if (overlayTv != null) {
                        overlayTv.setVisibility(View.GONE);
                    }
                    downloadButton.setText(decoratedBtnText);
                }
            }

            // 在下载管理找不到下载实体，到畅玩数据库里找
            if (downloadEntity == null) {
                String packageName = gameEntity.getUniquePackageName();
                if (!TextUtils.isEmpty(packageName)) {
                    downloadEntity = VHelper.getVDownloadEntitySnapshot(gameEntity.getId(), packageName);
                }
            }
        } else {
            // 非畅玩，显示为普通游戏
            if (context.getString(com.gh.gamecenter.feature.R.string.pluggable).equals(rawBtnText)) {
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.PLUGIN);
            } else if (context.getString(com.gh.gamecenter.feature.R.string.launch).equals(rawBtnText)) {
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
            } else if (context.getString(com.gh.gamecenter.feature.R.string.install).equals(rawBtnText)) {
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
            } else {
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            }

            if (showDualDownloadButton && viewHolder.getLocalDownloadSizeTv() != null) {
                viewHolder.getLocalDownloadSizeTv().setVisibility(View.GONE);
                String size = viewHolder.getGameEntity().getApk().isEmpty() ? "" : viewHolder.getGameEntity().getApk().get(0).getSize();
                if (size != null) {
                    String sizeWithoutDigit = convertSizeString(size);
                    viewHolder.getLocalDownloadSizeTv().setText(sizeWithoutDigit);
                }

                // 若双下载按钮时，下载的游戏是以畅玩游戏下载的，把 downloadEntity 置空，避免把按钮更新到错误的状态
                if (downloadEntity != null && ExtensionsKt.isVGameDownloadInDualDownloadMode(downloadEntity)) {
                    downloadEntity = null;
                }
            }

            String decoratedBtnText;
            String localBtnText;
            boolean useAlternativeTextStyle = false; // 是否使用带图标的文案，仅不包含补充文案时使用且

            // 更新下载按钮文案
            if (viewHolder.isNewsDetail()) {
                decoratedBtnText = rawBtnText;
                localBtnText = rawBtnText;
            } else if (context.getString(com.gh.gamecenter.feature.R.string.pluggable).equals(rawBtnText)) {
                decoratedBtnText = "升级" + (!containsAddWord ? "" : "至" + downloadAddWord) + getWrappedDownloadSizeText(viewHolder);
                localBtnText = "升级" + (!containsAddWord ? "" : "至" + downloadAddWord);
            } else if (context.getString(com.gh.gamecenter.feature.R.string.launch).equals(rawBtnText)) {
                decoratedBtnText = rawBtnText + (!containsAddWord ? "" : "-" + downloadAddWord);
                localBtnText = context.getString(com.gh.gamecenter.feature.R.string.launch_local);
            } else if (context.getString(com.gh.gamecenter.feature.R.string.attempt).equals(rawBtnText)) {
                decoratedBtnText = context.getString(com.gh.gamecenter.feature.R.string.attempt);
                localBtnText = rawBtnText;
                if (showDualDownloadButton
                        && viewHolder.getLocalDownloadContainer() != null
                        && viewHolder.getLocalDownloadContainer().getVisibility() == View.VISIBLE) {
                    viewHolder.getLocalDownloadSizeTv().setVisibility(View.VISIBLE);
                } else if (viewHolder.getOverlayTv() != null) {
                    useAlternativeTextStyle = true;
                }
            } else if (context.getString(com.gh.gamecenter.feature.R.string.install).equals(rawBtnText)) {
                decoratedBtnText = context.getString(com.gh.gamecenter.feature.R.string.install);
                localBtnText = context.getString(com.gh.gamecenter.feature.R.string.install_local);
            } else if (context.getString(com.gh.gamecenter.feature.R.string.update).equals(rawBtnText)) {
                decoratedBtnText = context.getString(com.gh.gamecenter.feature.R.string.update);
                localBtnText = context.getString(com.gh.gamecenter.feature.R.string.update_local);
                if (showDualDownloadButton
                        && viewHolder.getLocalDownloadContainer() != null
                        && viewHolder.getLocalDownloadContainer().getVisibility() == View.VISIBLE) {
                    viewHolder.getLocalDownloadSizeTv().setVisibility(View.VISIBLE);
                }
            } else {
                if (containsAddWord) {
                    decoratedBtnText = rawBtnText + downloadAddWord + getWrappedDownloadSizeText(viewHolder);
                } else {
                    decoratedBtnText = rawBtnText;
                }
                localBtnText = context.getString(com.gh.gamecenter.feature.R.string.download_local);
                if (showDualDownloadButton
                        && viewHolder.getLocalDownloadContainer() != null
                        && viewHolder.getLocalDownloadContainer().getVisibility() == View.VISIBLE) {
                    viewHolder.getLocalDownloadSizeTv().setVisibility(View.VISIBLE);
                } else if (viewHolder.getOverlayTv() != null && !containsAddWord) {
                    useAlternativeTextStyle = true;
                }
            }

            if (useAlternativeTextStyle) {
                downloadButton.setText("");
                viewHolder.getOverlayTv().setText(decoratedBtnText);
                viewHolder.getOverlayTv().setVisibility(View.VISIBLE);
                viewHolder.getOverlayTv().setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_special_download, 0, 0, 0);
                if (viewHolder.getExtraOverlayTv() != null) {
                    viewHolder.getExtraOverlayTv().setVisibility(View.VISIBLE);
                    viewHolder.getExtraOverlayTv().setText(gameEntity.getApk().get(0).getSize());
                }
            } else {
                if (viewHolder.getOverlayTv() != null && !showDualDownloadButton) {
                    viewHolder.getOverlayTv().setVisibility(View.GONE);
                    if (viewHolder.getExtraOverlayTv() != null) {
                        viewHolder.getExtraOverlayTv().setVisibility(View.GONE);
                    }
                }
                downloadButton.setText(decoratedBtnText);
            }

            if (viewHolder.getLocalDownloadTitleTv() != null) {
                viewHolder.getLocalDownloadTitleTv().setText(localBtnText);
            }
        }

        if (overlayTv != null && overlayTv.getVisibility() == View.VISIBLE) {
            downloadButton.setTag(com.gh.gamecenter.feature.R.string.download, overlayTv.getText());
        } else {
            downloadButton.setTag(com.gh.gamecenter.feature.R.string.download, downloadButton.getText());
        }

        if (downloadEntity == null) return;

        if (handleDownloadButtonAsXapk(downloadEntity, downloadButton)) {
            return;
        }

        // 非完成状态显示下载按钮
        if (downloadEntity.getStatus() != DownloadStatus.done) {
            viewHolder.getDownloadPb().setVisibility(View.VISIBLE);
        }

        // 存在未完成的下载任务或不显示双按钮时，隐藏本地下载按钮
        if (viewHolder.getLocalDownloadContainer() != null) {
            if (downloadEntity.getStatus() != DownloadStatus.done) {
                viewHolder.getLocalDownloadContainer().setVisibility(View.GONE);
            } else if (showDualDownloadButton) {
                viewHolder.getLocalDownloadContainer().setVisibility(View.VISIBLE);
            } else {
                viewHolder.getLocalDownloadContainer().setVisibility(View.GONE);
            }
        }

        downloadButton.setProgress((int) (downloadEntity.getPercent() * 10));

        if (overlayTv != null
                && downloadEntity.getStatus() != DownloadStatus.done) {
            overlayTv.setVisibility(View.GONE);
            if (viewHolder.getExtraOverlayTv() != null) {
                viewHolder.getExtraOverlayTv().setVisibility(View.GONE);
            }
        }

        if (showAsVGame) {
            updateVStyleDownloadButton(viewHolder, downloadButton, downloadEntity, rawBtnText);
        } else {
            updateDefaultStyleDownloadButton(context, viewHolder, downloadButton, gameEntity, downloadEntity);
        }
    }

    /**
     * 根据预置的配置更新 ViewHolder 的状态
     *
     * @return 是否已经是最终状态，返回 true 表示已应用当前配置，返回 false 表示不应用当前配置
     */
    private static boolean updateViewHolderWithPredefinedConfig(DetailViewHolder viewHolder, GameEntity gameEntity) {
        String downloadAddWord = gameEntity.getDownloadAddWord();

        // 不满足条件的部分游戏隐藏下载按钮
        if (!"光环助手".equals(gameEntity.getName())) {
            viewHolder.getDownloadBottom().setVisibility(View.VISIBLE);
        } else {
            viewHolder.getDownloadBottom().setVisibility(View.GONE);
            return true;
        }

        // 青少年模式显示为查看
        if (SPUtils.getBoolean(Constants.SP_TEENAGER_MODE)) {
            viewHolder.getDownloadPb().setText("查看");
            viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.TEENAGER_MODE);
            return true;
        }

        // 预约
        if (gameEntity.isReservable()) {
            if (!ReservationRepository.thisGameHasBeenReserved(gameEntity.getId())) {
                if (TextUtils.isEmpty(downloadAddWord)) {
                    viewHolder.getDownloadPb().setText(String.format("预约" + "《%s》", gameEntity.getName()));
                } else {
                    viewHolder.getDownloadPb().setText(String.format("预约" + "《%s》%s", gameEntity.getName(), downloadAddWord));
                }
                viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.RESERVABLE);
            } else {
                viewHolder.getDownloadPb().setText("已预约《" + gameEntity.getName() + "》");
                viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.RESERVED);
            }
            return true;
        }

        // 国际服 H5 弹窗
        final RegionSetting.GameH5Download gameH5Download = RegionSettingHelper.getGameH5DownloadByGameId(gameEntity.getId());
        if (gameH5Download != null) {
            viewHolder.getDownloadPb().setText(TextUtils.isEmpty(gameEntity.getDownloadOffText()) ? "查看详情" : gameEntity.getDownloadOffText());
            viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            return true;
        }

        // 特殊下载
        if (gameEntity.isSpecialDownload()) {
            viewHolder.getDownloadPb().setText("查看下载资源");
            viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.SPECIAL_DOWNLOAD);
            return true;
        }

        // 处理不存在 APK 文件或游戏状态为关闭时的情况
        if (gameEntity.getApk().isEmpty() || gameEntity.getDownloadOffStatus() != null) {
            LinkEntity h5LinkEntity = gameEntity.getH5Link();

            if (h5LinkEntity != null) {
                if ("play".equals(h5LinkEntity.getType())) {
                    String defaultString = String.format("开始玩" + "《%s》", gameEntity.getName());
                    viewHolder.getDownloadPb().setText(TextUtils.isEmpty(h5LinkEntity.getText()) ? defaultString : h5LinkEntity.getText());
                } else {
                    viewHolder.getDownloadPb().setText(TextUtils.isEmpty(h5LinkEntity.getText()) ? "查看" : h5LinkEntity.getText());
                }
                viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.H5_GAME);
            } else {
                if ("dialog".equals(gameEntity.getDownloadOffStatus()) || "third_party".equals(gameEntity.getDownloadOffStatus())) {
                    viewHolder.getDownloadPb().setText(TextUtils.isEmpty(gameEntity.getDownloadOffText()) ? "查看详情" : gameEntity.getDownloadOffText());
                    viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.NONE_WITH_HINT);
                } else if ("updating".equals(gameEntity.getDownloadOffStatus())) {
                    viewHolder.getDownloadPb().setText(TextUtils.isEmpty(gameEntity.getDownloadOffText()) ? "更新中" : gameEntity.getDownloadOffText());
                    viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.UPDATING);
                } else {
                    viewHolder.getDownloadPb().setText(TextUtils.isEmpty(gameEntity.getDownloadOffText()) ? "暂无下载" : gameEntity.getDownloadOffText());
                    viewHolder.getDownloadPb().setButtonStyle(DownloadButton.ButtonStyle.NONE);
                }
            }
            return true;
        }
        return false;
    }

    private static String getWrappedDownloadSizeText(DetailViewHolder viewHolder) {
        return String.format("（%s）", viewHolder.getGameEntity().getApk().isEmpty() ? "" : viewHolder.getGameEntity().getApk().get(0).getSize());
    }

    private static void updateVStyleDownloadButton(DetailViewHolder viewHolder,
                                                   DownloadButton downloadButton,
                                                   DownloadEntity downloadEntity,
                                                   String status) {
        switch (downloadEntity.getStatus()) {
            case redirected:
            case downloading:
                downloadButton.setText(SpeedUtils.getSpeed(downloadEntity.getSpeed()));
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                break;
            case waiting:
                downloadButton.setText(com.gh.gamecenter.feature.R.string.waiting);
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.WAITING);
                break;
            case overflow:
            case timeout:
            case neterror:
            case subscribe:
            case diskisfull:
            case diskioerror:
            case pause:
                String pausedText = viewHolder.getContext().getString(com.gh.gamecenter.feature.R.string.paused);
                downloadButton.setText(getValidProgress(downloadEntity) + "% " + pausedText);
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                break;
            case done:
                String updateText = viewHolder.getContext().getString(com.gh.gamecenter.feature.R.string.update);
                if (!status.contains(updateText)) {
                    if (VHelper.isInstalled(downloadEntity.getPackageName())) {
                        downloadButton.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
                    } else {
                        downloadButton.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                    }

                    downloadButton.setText("");
                }
                break;
            case cancel:
            case hijack:
            case notfound:
            case uncertificated:
            case unqualified:
            case unavailable:
            case banned:
                updateViewHolder(viewHolder, true);
                break;
            default:
                break;
        }
    }

    private static void updateDefaultStyleDownloadButton(
            Context context,
            DetailViewHolder viewHolder,
            DownloadButton downloadButton,
            GameEntity gameEntity,
            DownloadEntity downloadEntity) {
        switch (downloadEntity.getStatus()) {
            case timeout:
            case neterror:
            case subscribe:
            case downloading:
            case redirected:
            case pause:
            case diskisfull:
            case diskioerror:
            case overflow:
                String pausedText = context.getString(com.gh.gamecenter.feature.R.string.paused);
                String downloadingText = SpeedUtils.getSpeed(downloadEntity.getSpeed());
                String resumeText = getValidProgress(downloadEntity) + "% " + pausedText;
                downloadButton.setText((downloadEntity.getStatus() == DownloadStatus.downloading || downloadEntity.getStatus() == DownloadStatus.redirected) ? downloadingText : resumeText);
                if (downloadEntity.isPluggable() && PackagesManager.isInstalled(downloadEntity.getPackageName())) {
                    downloadButton.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_PLUGIN);
                } else {
                    downloadButton.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                }
                break;
            case waiting:
                downloadButton.setText(com.gh.gamecenter.feature.R.string.waiting);
                downloadButton.setButtonStyle(DownloadButton.ButtonStyle.WAITING);
                break;
            case done:
                if (SimulatorGameManager.isSimulatorGame(gameEntity)) {
                    boolean isInstalled = PackageUtils.isInstalledFromAllPackage(context, gameEntity.getSimulator().getApk().getPackageName());
                    boolean isInstalledNewSimulator = SimulatorGameManager.isNewSimulatorInstalled(context);
                    if (isInstalled || isInstalledNewSimulator) {
                        downloadButton.setText(com.gh.gamecenter.feature.R.string.launch);
                        downloadButton.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
                    } else {
                        if (SPUtils.getBoolean(Constants.SP_USE_BROWSER_TO_INSTALL) && !Objects.equals(Constants.XAPK_APKS_FORMAT, downloadEntity.getFormat())) {
                            downloadButton.setText(com.gh.gamecenter.feature.R.string.browser_install_install);
                        } else {
                            downloadButton.setText(com.gh.gamecenter.feature.R.string.install);
                        }
                        downloadButton.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                    }
                } else {
                    if (SPUtils.getBoolean(Constants.SP_USE_BROWSER_TO_INSTALL) && !Objects.equals(Constants.XAPK_APKS_FORMAT, downloadEntity.getFormat())) {
                        downloadButton.setText(com.gh.gamecenter.feature.R.string.browser_install_install);
                    } else {
                        downloadButton.setText(com.gh.gamecenter.feature.R.string.install);
                    }
                }

                break;
            case cancel:
            case hijack:
            case notfound:
            case uncertificated:
            case unqualified:
            case unavailable:
            case banned:
                updateViewHolder(viewHolder, true);
                break;
            default:
                break;
        }
    }

    public static int getValidProgress(DownloadEntity downloadEntity) {
        return (int) Math.ceil(downloadEntity.getPercent());
    }

    public static String convertSizeString(String sizeString) {
        String numberPart;
        String indicator;

        // Check if the string ends with "MB"
        if (sizeString.endsWith("MB")) {
            numberPart = sizeString.substring(0, sizeString.length() - 2);
            indicator = "MB";
        } else if (sizeString.endsWith("G")) {
            numberPart = sizeString.substring(0, sizeString.length() - 1);
            indicator = "G";
        } else {
            return sizeString;
        }

        // Round number
        double number = Double.parseDouble(numberPart);
        long roundedNumber = Math.round(number);

        // Combine rounded number and size indicator
        return roundedNumber + indicator;
    }


    private static boolean handleDownloadButtonAsXapk(DownloadEntity downloadEntity, DownloadButton downloadButton) {
        String xapkStatus = downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_STATUS);

        if (XapkUnzipStatus.SUCCESS.name().equals(xapkStatus) && XapkInstaller.INSTANCE.isInstalling(downloadEntity.getPath())) {
            downloadButton.setText("游戏安装中");
            downloadButton.setProgress(100);
            downloadButton.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
            return true;
        }

        if (XapkUnzipStatus.UNZIPPING.name().equals(xapkStatus)) {
            String percent = downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_PERCENT);
            downloadButton.setText("游戏解压中 " + percent + "%");
            downloadButton.setProgress((int) (Float.valueOf(percent) * 10));
            downloadButton.setButtonStyle(DownloadButton.ButtonStyle.XAPK_UNZIPPING);
            return true;
        } else if (XapkUnzipStatus.FAILURE.name().equals(xapkStatus)) {
            downloadButton.setText(com.gh.gamecenter.feature.R.string.install);
            downloadButton.setButtonStyle(DownloadButton.ButtonStyle.XAPK_FAILURE);
            return true;
        }

        return false;
    }
}
