package com.gh.common.util;

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

import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;

import com.gh.common.constant.Config;
import com.gh.common.simulator.SimulatorGameManager;
import com.gh.common.view.DownloadButton;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.core.AppExecutor;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.ApkLink;
import com.gh.gamecenter.entity.GameCollectionEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.entity.PluginLocation;
import com.gh.gamecenter.entity.SettingsEntity;
import com.gh.gamecenter.manager.PackagesManager;
import com.gh.vspace.VHelper;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;

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

public class GameUtils {

    /**
     * 去除与重复sourceList相同的数据
     */
    public static List<GameEntity> removeDuplicateData(List<GameEntity> sourceList, List<GameEntity> rawList) {
        if (sourceList == null || sourceList.isEmpty()
                || rawList == null || rawList.isEmpty()) {
            return rawList;
        }
        String id;
        for (int i = 0; i < rawList.size(); i++) {
            id = rawList.get(i).getId();
            for (GameEntity gameEntity : sourceList) {
                if (id.equals(gameEntity.getId())) {
                    rawList.remove(i);
                    i--;
                    break;
                }
            }
        }
        return rawList;
    }

    /**
     * 设置下载按钮状态
     */
    public static void setDownloadBtnStatus(Context context, GameEntity gameEntity, DownloadButton downloadBtn, PluginLocation pluginLocation) {
        // getDownloadBtnText 里包括查询数据库、根据包名读取包体 meta 信息等
        AppExecutor.getLightWeightIoExecutor().execute(() -> {
            String status = getDownloadBtnText(context, gameEntity, pluginLocation);
            AppExecutor.getUiExecutor().execute(() -> {
                downloadBtn.setText(status);
                if (context.getString(R.string.pluggable).equals(status)) {
                    downloadBtn.setButtonStyle(DownloadButton.ButtonStyle.PLUGIN);
                    String pluginDesc = gameEntity.getPluginDesc();
                    if (pluginDesc.length() > 3) pluginDesc = pluginDesc.substring(0, 3);
                    downloadBtn.setText((pluginDesc + "化"));
                } else {
                    downloadBtn.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
                }
            });
        });
    }

    /**
     * 获取下载按钮文案 (相对耗时，请优先在子线程调用)
     */
    @WorkerThread
    public static String getDownloadBtnText(Context context, GameEntity gameEntity, PluginLocation pluginLocation) {
        if (gameEntity.getApk().size() > 1) {
            return "";
        }

        int doneCount = 0;      // 下载完成数量
        int pluginCount = 0;    // 可插件化数量
        int updateCount = 0;    // 可更新数量
        int installCount = 0;   // 已安装数量

        boolean isRelatedEmulatorInstalled = false; // 若该游戏是模拟器游戏时其对应的模拟器是否已经安装
        boolean isInstalledNewSimulator = false;// 是否安装新模拟器
        DownloadEntity downloadEntity = null;
        Object gh_id;
        apkFor:
        for (ApkEntity apkEntity : gameEntity.getApk()) {

            // filter by packageName
            SettingsEntity settings = Config.getSettings();
            if (settings != null && gameEntity.getApk().size() > 1) {
                for (String pkgName : settings.getGameDownloadBlackList()) {
                    if (pkgName.equals(apkEntity.getPackageName())) {
                        continue apkFor;
                    }
                }
            }

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

            // 在下载管理找不到下载实体，并且为畅玩游戏的时候到畅玩数据库里找
            if (downloadEntity == null && gameEntity.isVGame()) {
                downloadEntity = VHelper.getDownloadEntitySnapshot(gameEntity.getId(), apkEntity.getPackageName());
            }

            if (downloadEntity != null) {
                if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
                    doneCount++;
                } else if (downloadEntity.isPluggable()) {
                    pluginCount++;
                } else if (downloadEntity.isUpdate()) {
                    updateCount++;
                }
            }
            if (PackagesManager.INSTANCE.isCanUpdate(gameEntity.getId(), apkEntity.getPackageName())) {
                updateCount++;
            }
            if (PackagesManager.isInstalled(apkEntity.getPackageName())) {
                gh_id = PackageUtils.getMetaData(context, apkEntity.getPackageName(), "gh_id");
                if (!TextUtils.isEmpty(apkEntity.getGhVersion())
                        && !PackageUtils.isSignedByGh(context, apkEntity.getPackageName())
                        && apkEntity.isShowPlugin(pluginLocation)) {
                    pluginCount++;
                } else if (gh_id == null
                        || gh_id.equals(gameEntity.getId())
                        // 当使用镜像时，可能会存在镜像 gh_id 与当前游戏 id 不一样的情况，这时也让它通过，避免装完还是显示`下载`
                        || gameEntity.shouldUseMirrorInfo()) {
                    installCount++;
                }
            }
            if (SimulatorGameManager.isSimulatorGame(gameEntity)) {
                isInstalledNewSimulator = SimulatorGameManager.isNewSimulatorInstalled(context);
                DownloadEntity simulatorDownloadEntity = SimulatorGameManager.findDownloadEntityByUrl(apkEntity.getUrl());
                if (simulatorDownloadEntity != null && gameEntity.getSimulator() != null) {
                    boolean isInstalled = PackageUtils.isInstalledFromAllPackage(context, gameEntity.getSimulator().getApk().getPackageName());
                    if (isInstalled) {
                        installCount++;
                        isRelatedEmulatorInstalled = true;
                    } else {
                        doneCount++;
                    }
                }
            }
        }
        if ((isRelatedEmulatorInstalled || isInstalledNewSimulator) && doneCount != 0) {
            return context.getString(R.string.launch);
        }

        if (gameEntity.isVGame()) {
            // 如果 doneCount 为 0 或者数据库为空
            // 表明本地并没有此游戏的数据库数据，需要重新下载
            if (doneCount == 0
                    || downloadEntity == null
                    || !VHelper.isInstalled(downloadEntity.getPackageName())) {
                installCount = 0;
            } else {
                doneCount = 0;
                installCount = 1;
            }
        }

        if (doneCount != 0) {
            return context.getString(R.string.install);
        } else if (pluginCount != 0 && !SimulatorGameManager.isSimulatorGame(gameEntity)) {
            return context.getString(R.string.pluggable);
        } else if (updateCount != 0 && !SimulatorGameManager.isSimulatorGame(gameEntity)) {
            return context.getString(R.string.update);
        } else if (installCount != 0) {
            return context.getString(R.string.launch);
        } else if ("demo".equals(gameEntity.getDownloadStatus())) {
            return context.getString(R.string.attempt);
        } else {
            if (gameEntity.isVGame()) {
                return context.getString(R.string.smooth);
            } else {
                return context.getString(R.string.download);
            }
        }
    }

    /**
     * 获取GameUpdateEntity(插件化)
     */
    public static GameUpdateEntity getGameUpdateEntity(GameEntity gameEntity, ApkEntity apkEntity) {
        GameUpdateEntity gameUpdateEntity = new GameUpdateEntity();
        gameUpdateEntity.setId(gameEntity.getId());
        gameUpdateEntity.setIcon(gameEntity.getIcon());
        gameUpdateEntity.setRawIcon(gameEntity.getRawIcon());
        gameUpdateEntity.setIconSubscript(gameEntity.getIconSubscript());
        gameUpdateEntity.setName(gameEntity.getName());
        gameUpdateEntity.setPackageName(apkEntity.getPackageName());
        gameUpdateEntity.setSize(apkEntity.getSize());
        gameUpdateEntity.setVersion(apkEntity.getVersion());
        gameUpdateEntity.setGhVersion(apkEntity.getGhVersion());
        gameUpdateEntity.setUrl(apkEntity.getUrl());
        gameUpdateEntity.setPlatform(apkEntity.getPlatform());
        gameUpdateEntity.setEtag(apkEntity.getEtag());
        gameUpdateEntity.setPluggable(true);
        gameUpdateEntity.setTagStyle(gameEntity.getTagStyle());
        gameUpdateEntity.setBrief(gameEntity.getBrief());
        gameUpdateEntity.setPlugin(apkEntity.getPlugin());
        gameUpdateEntity.setDownload(gameEntity.getDownload());
        gameUpdateEntity.setIndexPlugin(gameEntity.getIndexPlugin());
        gameUpdateEntity.setPluginDesc(gameEntity.getPluginDesc());
        gameUpdateEntity.setFormat(apkEntity.getFormat());
        gameUpdateEntity.setCurrentVersion(PackageUtils.getVersionNameByPackageName(apkEntity.getPackageName()));
        gameUpdateEntity.setCategory(gameEntity.getCategory());

        GameCollectionEntity pluggableCollection = getPluggableCollectionFromGameEntity(gameEntity, apkEntity.getPackageName());
        if (pluggableCollection != null) {
            gameUpdateEntity.setPluggableCollection(pluggableCollection);
        }
        return gameUpdateEntity;
    }

    @Nullable
    public static GameCollectionEntity getPluggableCollectionFromGameEntity(GameEntity gameEntity, String targetPkg) {
        // 添加插件化包所在的合集
        for (GameCollectionEntity collectionEntity : gameEntity.getCollection()) {
            if (collectionEntity.getPackages().contains(targetPkg)) {
                ArrayList<ApkEntity> saveApkEntity = new ArrayList<>();
                for (String pkg : collectionEntity.getPackages()) {
                    for (ApkEntity apk : gameEntity.getApk()) {
                        if (pkg.equals(apk.getPackageName())) {
                            saveApkEntity.add(apk);
                            break;
                        }
                    }
                }

                ArrayList<ApkLink> apkLinks = gameEntity.getApkLink();
                if (apkLinks != null) {
                    for (ApkLink apkLink : apkLinks) {
                        if (apkLink.getCollection().equals(collectionEntity.getId())) {
                            ApkEntity element = new ApkEntity();
                            element.setApkLink(apkLink);
                            if (saveApkEntity.size() > apkLink.getSort()) {
                                saveApkEntity.add(apkLink.getSort(), element);
                            } else {
                                saveApkEntity.add(element);
                            }
                        }
                    }
                }

                collectionEntity.setSaveApkEntity(saveApkEntity);
                return collectionEntity;
            }
        }
        return null;
    }
}
