package com.ycgis.macall.personalcenter.m.provider;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;

import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.ycgis.macall.personalcenter.m.adapterbean.WorkAppBean;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;

import org.jetbrains.annotations.NotNull;

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

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * created by:   Macall
 * create time:  2023/11/3 9:31
 * copyright:    @ruansee.com
 * Describe:
 */
public class NativeAppProvider {
    private static final String CUSTOM_CACHE_APP_LIST = "cacheCustomAppList";
    /**
     * 需要过滤的应用名称
     */
    private static final String FILTER_APP_NAME = "陌生号码识别Print Service音频播放phoneservice桌面资源MyOS主题资源基本互动屏保Gestural Navigation BarFileBrowserCell Broadcast Service" +
            "系统配置更新计算器CameraExtensionsProxy系统 WLAN 资源Call Log Backup/Restore运营商默认应用软件包安装程序指纹服务System Resources Package图片编辑Live Wallpaper Picker" +
            "系统桌面电话服务主题管理服务急救信息SecCamService存储空间管理器系统跟踪配置拨号器关机闹钟LTE Broadcast ManagerGestural Navigation BarQCC-AUTHMGRzpub.resalsCaptivePortalLoginBluetooth MIDI Service" +
            "扫一扫双卡管理用户词典智能识屏录音机华为杂志锁屏系统切换系统通话管理通话设置相机ConfigUpdaterFIDO UAF ASMHwIndexSearchObserverService下载内容iConnect隐私空间androidhwext屏幕录制下载管理器" +
            "MmsServiceCompanion Device Manager外部存储设备HTML 查看器Huawei Secure IMEHwIntelligentRecSystem打印处理服务默认打印服务图库SmartcardService媒体存储设备HwChrServiceHwNearby" +
            "悬浮导航华为服务框架文件管理器通过蓝牙导入HwSynergyhiview设置建议电话和短信日历存储设置存储时钟拨号联系人存储短信浏览器华为手机助手手机管家中兴手机助手华为桌面手机管理主题系统界面通话/信息存储UEInfoCheck";

    private Context context;
    private List<String> selectPackageAppList;

    public NativeAppProvider(Context context, List<String> selectPackageAppList) {
        this.context = context;
        this.selectPackageAppList = selectPackageAppList;
    }

    /**
     * 读取本地全部应用列表
     *
     * @return List<WorkAppBean>
     */
    public List<WorkAppBean> checkInstallApps() {
        List<WorkAppBean> launcherIconPackageList = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        try {
            List<PackageInfo> packageInfos = pm.getInstalledPackages(0);
            for (int i = 0; i < packageInfos.size(); i++) {
                PackageInfo pkgInfo = packageInfos.get(i);
                ApplicationInfo appInfo = pkgInfo.applicationInfo;
                if (TextUtils.equals(context.getPackageName(), pkgInfo.packageName)) continue;
                String appName = appInfo.loadLabel(pm).toString();
                if (appName.startsWith("com")) continue;
                if (appName.startsWith("org")) continue;
                if (appName.startsWith("vendor")) continue;
                if (appName.startsWith("framework")) continue;
                if (appName.startsWith("huawei.android")) continue;
                if (appName.endsWith("中兴版")) continue;
                if (appName.endsWith("华为版")) continue;
                if (appName.startsWith("Android")) continue;
                if (appName.contains("游戏")) continue;
                if (appName.contains("Huawei")) continue;
                if (appName.contains("浏览器")) continue;
                if (appName.contains("音乐")) continue;
                if (appName.contains("视频")) continue;
                if (FILTER_APP_NAME.contains(appName)) continue;
                Drawable applicationIcon = pm.getApplicationIcon(appInfo);
                WorkAppBean bean = new WorkAppBean();
                bean.setBaseType(1);
                bean.setApplicationIcon(applicationIcon);
                bean.setIcon(appInfo.icon);
                bean.setPackageName(pkgInfo.packageName);
                bean.setAppName(appName);
                LogUtils.w("本机应用名称",bean.getAppName());
                if (selectPackageAppList != null && !selectPackageAppList.isEmpty()) {
                    if (selectPackageAppList.contains(bean.getPackageName())) {
                        bean.setAdd(true);
                    }
                }
                launcherIconPackageList.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //
        }
        return launcherIconPackageList;
    }


    /**
     * 获取本地全部应用列表
     *
     * @param callback 异步回调
     */
    public void asyncCheckInstallApps(BaseRequestCallback<List<WorkAppBean>> callback) {
        Observable.create(new ObservableOnSubscribe<List<WorkAppBean>>() {
            @Override
            public void subscribe(@NotNull ObservableEmitter<List<WorkAppBean>> emitter) throws Exception {
                List<WorkAppBean> launcherIconPackageList = checkInstallApps();
                emitter.onNext(launcherIconPackageList);
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                //获得的数据返回主线程去更新界面
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<WorkAppBean>>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NotNull List<WorkAppBean> packageInfo) {
                        callback.onRequestSuccess(packageInfo);
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {
                        callback.onRequestFailure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private static Intent getLaunchIntent(PackageManager pm, String pkg) {
        Intent intent = pm.getLaunchIntentForPackage(pkg);
        if (intent != null) {
            return intent;
        } else {
            intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setPackage(pkg);
            List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);
            if (apps == null || apps.isEmpty()) {
                return null;
            }
            ResolveInfo ri = apps.iterator().next();
            if (ri == null) {
                return null;
            }
            intent.setComponent(new ComponentName(pkg, ri.activityInfo.name));
            return intent;
        }
    }


    /**
     * 获取本地全部应用列表
     *
     * @param callback 异步回调
     */
    public void getSelCustomAppList(BaseRequestCallback<List<WorkAppBean>> callback) {
        Observable.create((ObservableOnSubscribe<List<WorkAppBean>>) emitter -> {
            List<WorkAppBean> launcherIconPackageList = getSelCustomAppList();
            emitter.onNext(launcherIconPackageList);
            emitter.onComplete();
        })
                .subscribeOn(Schedulers.io())
                //获得的数据返回主线程去更新界面
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<WorkAppBean>>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NotNull List<WorkAppBean> packageInfos) {
                        callback.onRequestSuccess(packageInfos);
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {
                        callback.onRequestFailure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 读取本地全部应用列表
     *
     * @return List<WorkAppBean>
     */
    public List<WorkAppBean> getSelCustomAppList() {
        List<WorkAppBean> launcherIconPackageList = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        try {
            List<PackageInfo> packageInfos = pm.getInstalledPackages(0);
            String cacheCustomAppList = RuanseeApplication.getStringValue(CUSTOM_CACHE_APP_LIST);
            if (StringUtil.isNullOrEmpty(cacheCustomAppList)) return launcherIconPackageList;
            for (int i = 0; i < packageInfos.size(); i++) {
                PackageInfo pkgInfo = packageInfos.get(i);
                ApplicationInfo appInfo = pkgInfo.applicationInfo;
                if (TextUtils.equals(context.getPackageName(), pkgInfo.packageName)) continue;
                if (cacheCustomAppList.contains(pkgInfo.packageName)) {
                    Drawable applicationIcon = pm.getApplicationIcon(appInfo);
                    WorkAppBean bean = new WorkAppBean();
                    bean.setBaseType(1);
                    bean.setApplicationIcon(applicationIcon);
                    bean.setIcon(appInfo.icon);
                    bean.setPackageName(pkgInfo.packageName);
                    bean.setAppName(appInfo.loadLabel(pm).toString());
                    launcherIconPackageList.add(bean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //
        }
        return launcherIconPackageList;
    }

    public static void cacheCustomAppList(boolean isAdd, String packageName) {
        String cacheCustomAppList = RuanseeApplication.getStringValue(CUSTOM_CACHE_APP_LIST);
        if (isAdd) {
            if (StringUtil.isNullOrEmpty(cacheCustomAppList)) {
                cacheCustomAppList = packageName;
            } else {
                if (cacheCustomAppList.contains(packageName)) return;
                cacheCustomAppList += ";" + packageName;
            }
        } else {
            cacheCustomAppList = cacheCustomAppList.replace(";" + packageName, "").replace(packageName + ";", "");
        }
        RuanseeApplication.saveData(CUSTOM_CACHE_APP_LIST, cacheCustomAppList);
    }
}
