package com.gh.gamecenter.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import com.gh.common.util.InstallUtils;
import com.gh.common.util.PackageHelper;
import com.gh.common.util.PackageUtils;
import com.gh.download.DownloadManager;
import com.gh.download.PackageObserver;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.NewFlatLogUtils;
import com.gh.gamecenter.common.utils.SensorsBridge;
import com.gh.gamecenter.core.AppExecutor;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.dsp.DspReportHelper;
import com.gh.gamecenter.entity.NewApiSettingsEntity;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.feature.entity.GameInstall;
import com.gh.gamecenter.manager.PackagesManager;
import com.halo.assistant.HaloApp;
import com.lightgame.download.DownloadEntity;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.EventBus;

/**
 * 监听安装包变更
 */
public class PackageChangeBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "PackageChangeBroadcastReceiver";

    private static final String webviewPackageName = "com.google.android.webview";

    private final NewApiSettingsEntity.PackageObserveActions mActions;

    public PackageChangeBroadcastReceiver(NewApiSettingsEntity.PackageObserveActions actions) {
        mActions = actions;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        PackageHelper.INSTANCE.dumpInstalledListCache();
        ExtensionsKt.doOnMainProcessOnly(() -> {
            Utils.log(TAG, "onReceive->" + intent.getAction() + "==" + intent.getDataString());
            // 接收安装广播
            if (intent.getAction().equals(mActions.getAdd())) {
                String packageName = intent.getDataString();
                packageName = packageName.substring(packageName.indexOf(":") + 1);
                Utils.log(TAG, "安装了:" + packageName + "包名的程序");
                DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshotByPackageName(packageName);
                String gameId = downloadEntity != null && downloadEntity.getGameId() != null ? downloadEntity.getGameId() : "";
                String gameName = downloadEntity != null && downloadEntity.getName() != null ? downloadEntity.getName() : "";
                NewFlatLogUtils.INSTANCE.logGameInstallComplete(gameId, gameName);
                boolean isDspGame = downloadEntity != null && "true".equals(ExtensionsKt.getMetaExtra(downloadEntity, Constants.DSP_GAME));
                String dspAdId = downloadEntity == null ? "" : ExtensionsKt.getMetaExtra(downloadEntity, Constants.DSP_AD_ID);
                SensorsBridge.trackInstallGameFinish(
                        gameId,
                        gameName,
                        isDspGame,
                        dspAdId
                );

                if (isDspGame && !dspAdId.isEmpty()) {
                    DspReportHelper.INSTANCE.report(ExtensionsKt.getMetaExtra(downloadEntity, Constants.INSTALL_URL));
                }

                InstallUtils.getInstance().removeInstall(packageName);
                PackageHelper.refreshLocalPackageList();

                String versionName = PackageUtils.getVersionNameByPackageName(packageName);
                EBPackage installEb = new EBPackage(EBPackage.TYPE_INSTALLED, packageName, versionName, false);
                if (PackageUtils.isAppOnForeground(context)) {
                    PackageObserver.onPackageChanged(installEb, null);
                    EventBus.getDefault().post(installEb);
                } else {
                    // 处于后台运行的时候尝试延迟 100 ms 再触发 onPackageChanged (猜测是引起 ANR 的原因)
                    AppExecutor.getUiExecutor().executeWithDelay(() -> {
                        PackageObserver.onPackageChanged(installEb, null);
                        EventBus.getDefault().post(installEb);
                    }, 100);
                }
                if (webviewPackageName.equals(packageName)) {
                    HaloApp.getInstance().getWebviewAbiList();
                }
            }

            // 接收卸载广播
            if (intent.getAction().equals(mActions.getRem())) {
                String packageName = intent.getDataString();
                packageName = packageName.substring(packageName.indexOf(":") + 1);
                Utils.log(TAG, "卸载了:" + packageName + "包名的程序");
                GameInstall install = PackagesManager.getInstalledData(packageName);
                String gameId = install != null && install.getId() != null ? install.getId() : "";
                String gameName = install != null && install.getName() != null ? install.getName() : "";
                NewFlatLogUtils.INSTANCE.logGameUninstallComplete(gameId, gameName);
                SensorsBridge.trackUnloadGameFinish(gameId, gameName);

                InstallUtils.getInstance().removeUninstall(packageName);
                PackageHelper.refreshLocalPackageList();

                EBPackage uninstallEb = new EBPackage(EBPackage.TYPE_UNINSTALLED, packageName, "", false);
                PackageObserver.onPackageChanged(uninstallEb, null);
                EventBus.getDefault().post(uninstallEb);
                if (webviewPackageName.equals(packageName)) {
                    SPUtils.remove(Constants.SP_WEBVIEW_ABI_LIST);
                    SPUtils.remove(Constants.SP_WEBVIEW_VERSION_CODE);
                }
            }

            // 接收替换广播
            if (intent.getAction().equals(mActions.getRep())) {
                String packageName = intent.getData().getSchemeSpecificPart();
                packageName = packageName.substring(packageName.indexOf(":") + 1);
                Utils.log(TAG, "替换了:" + packageName + "包名的程序");
                String versionName = PackageUtils.getVersionNameByPackageName(packageName);

                EBPackage updateEb = new EBPackage(EBPackage.TYPE_REPLACED, packageName, versionName, false);
                EventBus.getDefault().post(updateEb);
                PackageObserver.onPackageChanged(updateEb, null);
                if (webviewPackageName.equals(packageName)) {
                    HaloApp.getInstance().getWebviewAbiList();
                }
            }
            return null;
        });
    }

}
