package com.gh.common.util;

import android.text.TextUtils;
import android.view.View;

import com.gh.common.constant.Config;
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.view.DownloadButton;
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.entity.PluginLocation;
import com.gh.gamecenter.manager.PackagesManager;
import com.gh.vspace.VHelper;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;

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

public class DetailDownloadUtils {

    public static void detailInitDownload(DetailViewHolder viewHolder, boolean isCheck) {
        String downloadAddWord = viewHolder.gameEntity.getDownloadAddWord();

        if (viewHolder.getOverlayTv() != null) {
            viewHolder.getOverlayTv().setVisibility(View.GONE);
        }

        if (viewHolder.mMultiVersionDownloadTv != null) {
            viewHolder.mMultiVersionDownloadTv.setVisibility(View.GONE);
        }

        if (viewHolder.gameEntity != null
                && Config.isShowDownload(viewHolder.gameEntity.getId())
                && !"光环助手".equals(viewHolder.gameEntity.getName())) {
            viewHolder.downloadBottom.setVisibility(View.VISIBLE);
        } else {
            viewHolder.downloadBottom.setVisibility(View.GONE);
            return;
        }

        if (SPUtils.getBoolean(Constants.SP_TEENAGER_MODE)) {
            viewHolder.mDownloadPb.setText("查看");
            viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.TEENAGER_MODE);
            return;
        }

        if (viewHolder.gameEntity.isSpecialDownload()) {
            viewHolder.mDownloadPb.setText("查看下载资源");
            viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.SPECIAL_DOWNLOAD);
            return;
        }

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

        final RegionSetting.GameH5Download gameH5Download = RegionSettingHelper.getGameH5DownloadByGameId(viewHolder.gameEntity.getId());
        if (gameH5Download != null) {
            viewHolder.mDownloadPb.setText(TextUtils.isEmpty(viewHolder.gameEntity.getDownloadOffText()) ? "查看详情" : viewHolder.gameEntity.getDownloadOffText());
            viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            return;
        }

        if (viewHolder.gameEntity.isVGame() && !viewHolder.gameEntity.getApk().isEmpty()) {
            String status = GameUtils.getDownloadBtnText(viewHolder.context, viewHolder.gameEntity, PluginLocation.only_game);
            if (viewHolder.context.getString(R.string.launch).equals(status)) {
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
            } else if (viewHolder.context.getString(R.string.install).equals(status)) {
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
            } else {
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            }

            String downloadText;
            if (viewHolder.context.getString(R.string.launch).equals(status) || viewHolder.context.getString(R.string.install).equals(status) || viewHolder.context.getString(R.string.download).equals(status)) {
                downloadText = "";
                if (viewHolder.getOverlayTv() != null) {
                    viewHolder.getOverlayTv().setVisibility(View.VISIBLE);
                }
            } else if (viewHolder.context.getString(R.string.attempt).equals(status)) {
                downloadText = status + getDownloadSizeText(viewHolder);
            } else {
                downloadText = status + (TextUtils.isEmpty(downloadAddWord) ? "" : downloadAddWord) + getDownloadSizeText(viewHolder);
            }
            viewHolder.mDownloadPb.setText(downloadText);

            DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(viewHolder.gameEntity);

            // 在下载管理找不到下载实体，到畅玩数据库里找
            if (downloadEntity == null && viewHolder.gameEntity.isVGame()) {
                String packageName = viewHolder.gameEntity.getUniquePackageName();
                if (!TextUtils.isEmpty(packageName)) {
                    downloadEntity = VHelper.getDownloadEntitySnapshot(viewHolder.gameEntity.getId(), packageName);
                }
            }

            if (downloadEntity != null) {
                viewHolder.downloadEntity = downloadEntity;
                detailInvalidate(viewHolder);
            }

            return;
        }

        if (viewHolder.gameEntity.getApk().isEmpty() || viewHolder.gameEntity.getDownloadOffStatus() != null) {
            LinkEntity h5LinkEntity = viewHolder.gameEntity.getH5Link();

            if (h5LinkEntity != null) {
                if ("play".equals(h5LinkEntity.getType())) {
                    String defaultString = String.format("开始玩" + "《%s》", viewHolder.gameEntity.getName());
                    viewHolder.mDownloadPb.setText(TextUtils.isEmpty(h5LinkEntity.getText()) ? defaultString : h5LinkEntity.getText());
                } else {
                    viewHolder.mDownloadPb.setText(TextUtils.isEmpty(h5LinkEntity.getText()) ? "查看" : h5LinkEntity.getText());
                }
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.H5_GAME);
            } else {
                if ("dialog".equals(viewHolder.gameEntity.getDownloadOffStatus())) {
                    viewHolder.mDownloadPb.setText(TextUtils.isEmpty(viewHolder.gameEntity.getDownloadOffText()) ? "查看详情" : viewHolder.gameEntity.getDownloadOffText());
                    viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.NONE_WITH_HINT);
                } else if ("updating".equals(viewHolder.gameEntity.getDownloadOffStatus())) {
                    viewHolder.mDownloadPb.setText(TextUtils.isEmpty(viewHolder.gameEntity.getDownloadOffText()) ? "更新中" : viewHolder.gameEntity.getDownloadOffText());
                    viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.UPDATING);
                } else {
                    viewHolder.mDownloadPb.setText(TextUtils.isEmpty(viewHolder.gameEntity.getDownloadOffText()) ? "暂无下载" : viewHolder.gameEntity.getDownloadOffText());
                    viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.NONE);
                }
            }
        } else if (viewHolder.gameEntity.getApk().size() == 1) {
            String status = GameUtils.getDownloadBtnText(viewHolder.context, viewHolder.gameEntity, PluginLocation.only_game);
            if (viewHolder.context.getString(R.string.pluggable).equals(status)) {
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.PLUGIN);
            } else if (viewHolder.context.getString(R.string.launch).equals(status)) {
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
            } else if (viewHolder.context.getString(R.string.install).equals(status)) {
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
            } else {
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            }

            String downloadText;
            if (viewHolder.isNewsDetail) {
                downloadText = status;
            } else if (viewHolder.context.getString(R.string.pluggable).equals(status)) {
                downloadText = "升级" + (TextUtils.isEmpty(downloadAddWord) ? "" : "至" + downloadAddWord) + getDownloadSizeText(viewHolder);
            } else if (viewHolder.context.getString(R.string.launch).equals(status)) {
                downloadText = status + (TextUtils.isEmpty(downloadAddWord) ? "" : "-" + downloadAddWord);
            } else if (viewHolder.context.getString(R.string.attempt).equals(status)) {
                downloadText = status + getDownloadSizeText(viewHolder);
            } else if (viewHolder.context.getString(R.string.install).equals(status)) {
                downloadText = viewHolder.context.getString(R.string.install);
            } else {
                downloadText = status + (TextUtils.isEmpty(downloadAddWord) ? "" : downloadAddWord) + getDownloadSizeText(viewHolder);
            }
            viewHolder.mDownloadPb.setText(downloadText);
        } else {
            viewHolder.mMultiVersionDownloadTv.setText("选择下载你的版本" + (TextUtils.isEmpty(downloadAddWord) ? "" : "-" + downloadAddWord));
            viewHolder.mMultiVersionDownloadTv.setVisibility(View.VISIBLE);
            viewHolder.mDownloadPb.setText("");
            viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
            DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(viewHolder.gameEntity);
            if (downloadEntity != null) {
                switch (downloadEntity.getStatus()) {
                    case downloading:
                        viewHolder.mDownloadTips.setVisibility(View.VISIBLE);
                        ExtensionsKt.setDownloadTipsAnimation(viewHolder.mDownloadTips, true);
                        break;
                    case done:
                    case pause:
                    case waiting:
                    case timeout:
                    case subscribe:
                    case neterror:
                    case overflow:
                        viewHolder.mDownloadTips.setVisibility(View.VISIBLE);
                        ExtensionsKt.setDownloadTipsAnimation(viewHolder.mDownloadTips, false);
                        break;
                    default:
                        viewHolder.mDownloadTips.setVisibility(View.GONE);
                        break;
                }
            } else {
                viewHolder.mDownloadTips.setVisibility(View.GONE);
            }
        }

        if (isCheck && viewHolder.gameEntity.getApk().size() == 1) {
            DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(viewHolder.gameEntity);

            // 在下载管理找不到下载实体，到畅玩数据库里找
            if (downloadEntity == null && viewHolder.gameEntity.isVGame()) {
                String packageName = viewHolder.gameEntity.getUniquePackageName();
                if (!TextUtils.isEmpty(packageName)) {
                    downloadEntity = VHelper.getDownloadEntitySnapshot(viewHolder.gameEntity.getId(), packageName);
                }
            }

            if (downloadEntity != null) {
                viewHolder.downloadEntity = downloadEntity;
                detailInvalidate(viewHolder);
            }
        }
    }

    private static String getDownloadSizeText(DetailViewHolder viewHolder) {
        return String.format("（%s）", viewHolder.gameEntity.getApk().get(0).getSize());
    }

    public static void detailInvalidate(DetailViewHolder viewHolder) {
        DownloadEntity downloadEntity = viewHolder.downloadEntity;
        String xapkStatus = downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_STATUS);

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

        viewHolder.mDownloadPb.setProgress((int) (viewHolder.downloadEntity.getPercent() * 10));
        if (viewHolder.getOverlayTv() != null) {
            viewHolder.getOverlayTv().setVisibility(View.GONE);
        }

        if (viewHolder.gameEntity.isVGame()) {
            updateVStyleButton(viewHolder);
            return;
        }

        switch (downloadEntity.getStatus()) {
            case timeout:
            case neterror:
            case subscribe:
            case downloading:
            case redirected:
            case pause:
            case overflow:
                String downloadingText = "游戏加载中 " + downloadEntity.getPercent() + "%";
                String resumeText = "继续加载 " + downloadEntity.getPercent() + "%";
                viewHolder.mDownloadPb.setText((downloadEntity.getStatus() == DownloadStatus.downloading || downloadEntity.getStatus() == DownloadStatus.redirected) ? downloadingText : resumeText);
                if (downloadEntity.isPluggable() && PackagesManager.INSTANCE.isInstalled(downloadEntity.getPackageName())) {
                    viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_PLUGIN);
                } else {
                    viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                }
                break;
            case waiting:
                viewHolder.mDownloadPb.setText(R.string.waiting);
                if (downloadEntity.isPluggable() && PackagesManager.INSTANCE.isInstalled(downloadEntity.getPackageName())) {
                    viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.WAITING);
                } else {
                    viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.WAITING);
                }
                break;
            case done:
                if (SimulatorGameManager.isSimulatorGame(viewHolder.gameEntity)) {
                    boolean isInstalled = PackageUtils.isInstalledFromAllPackage(viewHolder.context, viewHolder.gameEntity.getSimulator().getApk().getPackageName());
                    boolean isInstalledNewSimulator = SimulatorGameManager.isNewSimulatorInstalled(viewHolder.context);
                    if (isInstalled || isInstalledNewSimulator) {
                        viewHolder.mDownloadPb.setText(R.string.launch);
                        viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
                    } else {
                        if (SPUtils.getBoolean(Constants.SP_USE_BROWSER_TO_INSTALL)) {
                            viewHolder.mDownloadPb.setText(R.string.browser_install_install);
                        } else {
                            viewHolder.mDownloadPb.setText(R.string.install);
                        }
                        viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                    }
                } else if (viewHolder.gameEntity.isVGame()) {
                    if (!viewHolder.mDownloadPb.getText().toString().contains("更新")) {
                        if (VHelper.isInstalled(downloadEntity.getPackageName())) {
                            viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
                        } else {
                            viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                        }

                        viewHolder.mDownloadPb.setText("");
                        if (viewHolder.getOverlayTv() != null) {
                            viewHolder.getOverlayTv().setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    if (SPUtils.getBoolean(Constants.SP_USE_BROWSER_TO_INSTALL)) {
                        viewHolder.mDownloadPb.setText(R.string.browser_install_install);
                    } else {
                        viewHolder.mDownloadPb.setText(R.string.install);
                    }
                    if (downloadEntity.isPluggable()
                            && PackagesManager.isInstalled(downloadEntity.getPackageName())) {
                        viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_PLUGIN);
                    } else {
                        viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                    }
                }

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

    private static void updateVStyleButton(DetailViewHolder viewHolder) {
        switch (viewHolder.downloadEntity.getStatus()) {
            case redirected:
            case downloading:
                viewHolder.mDownloadPb.setText("游戏加载中 " + viewHolder.downloadEntity.getPercent() + "%");
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                break;
            case waiting:
                viewHolder.mDownloadPb.setText(R.string.waiting);
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                break;
            case overflow:
            case timeout:
            case neterror:
            case subscribe:
            case pause:
                viewHolder.mDownloadPb.setText("继续加载 " + viewHolder.downloadEntity.getPercent() + "%");
                viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                break;
            case done:
                if (!viewHolder.mDownloadPb.getText().toString().contains("更新")) {
                    if (VHelper.isInstalled(viewHolder.downloadEntity.getPackageName())) {
                        viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
                    } else {
                        viewHolder.mDownloadPb.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                    }

                    viewHolder.mDownloadPb.setText("");
                    if (viewHolder.getOverlayTv() != null) {
                        viewHolder.getOverlayTv().setVisibility(View.VISIBLE);
                    }
                }
                break;
            default:
                break;
        }
    }
}
