package com.gh.common.util;


import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.gh.download.DownloadManager;
import com.gh.gamecenter.eventbus.EBPackage;
import com.halo.assistant.HaloApp;
import com.lightgame.download.DownloadEntity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 下载完成跳安装，
 */
public class InstallUtils {

    private static final int MAX_TIME = 5 * 60 * 1000;
    private static int INSTALL_WHAT = 20;

    private static Map<String, Long> installMap;
    private static Map<String, Long> uninstallMap;

    private PackageManager packageManager;
    private Handler handler;
    private boolean isRunning;

    private InstallUtils() {
        Context context = HaloApp.getInstance().getApplicationContext();

        isRunning = false;

        packageManager = context.getPackageManager();

        handler = new Handler(context.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == INSTALL_WHAT && packageManager != null) {
                    ArrayList<String> list = new ArrayList<>();
                    List<PackageInfo> packageInfos = PackageUtils.getInstalledPackages(context, 0);
                    for (PackageInfo packageInfo : packageInfos) {
                        if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                            list.add(packageInfo.packageName);
                        }
                    }
                    if (installMap != null && installMap.size() != 0) {
                        ArrayList<String> keys = new ArrayList<>();
                        for (String packageName : installMap.keySet()) {
                            long time = installMap.get(packageName);
                            if (System.currentTimeMillis() - time >= MAX_TIME) {
                                keys.add(packageName);
                            } else if (list.contains(packageName)) {
                                keys.add(packageName);

                                DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntityByPackageName(packageName);
                                String installVersion = PackageUtils.getVersionNameByPackageName(packageName);
                                if (!TextUtils.isEmpty(installVersion) && downloadEntity != null &&
                                        installVersion.equals(downloadEntity.getVersionName())) {
                                    if (!downloadEntity.isPluggable() || PackageUtils.isSignedByGh(context, packageName)) {
                                        EventBus.getDefault().post(new EBPackage(EBPackage.TYPE_INSTALLED, packageName, installVersion));
                                    }
                                }
                            }
                        }
                        for (String key : keys) {
                            installMap.remove(key);
                        }
                    }
                    if (uninstallMap != null && uninstallMap.size() != 0) {
                        ArrayList<String> keys = new ArrayList<>();
                        for (String packageName : uninstallMap.keySet()) {
                            long time = uninstallMap.get(packageName);
                            if (System.currentTimeMillis() - time >= MAX_TIME) {
                                keys.add(packageName);
                            } else if (!list.contains(packageName)) {
                                keys.add(packageName);
                                EventBus.getDefault().post(new EBPackage("卸载", packageName, ""));
                            }
                        }
                        for (String key : keys) {
                            uninstallMap.remove(key);
                        }
                    }
                    if ((installMap != null && installMap.size() != 0)
                            || (uninstallMap != null && uninstallMap.size() != 0)) {
                        sendEmptyMessageDelayed(INSTALL_WHAT, 3000);
                    } else {
                        isRunning = false;
                    }
                }
            }
        };
    }

    public static InstallUtils getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void addInstall(String packageName) {
        if (installMap == null) {
            installMap = Collections.synchronizedMap(new HashMap<String, Long>());
        }
        installMap.put(packageName, System.currentTimeMillis());
        run();
    }

    public void run() {
        if ((installMap == null || installMap.isEmpty()) && (uninstallMap == null || uninstallMap.isEmpty())) {
            return;
        }
        if (isRunning) {
            return;
        }
        isRunning = true;
        handler.sendEmptyMessageDelayed(INSTALL_WHAT, 10000);
    }

    public void removeInstall(String packageName) {
        if (installMap != null) {
            installMap.remove(packageName);
        }
    }

    public void addUninstall(String packageName) {
        if (uninstallMap == null) {
            uninstallMap = Collections.synchronizedMap(new HashMap<String, Long>());
        }
        uninstallMap.put(packageName, System.currentTimeMillis());
        run();
    }

    public void removeUninstall(String packageName) {
        if (uninstallMap != null) {
            uninstallMap.remove(packageName);
        }
    }

    private static class SingletonHolder {
        private static final InstallUtils INSTANCE = new InstallUtils();
    }
}
