package com.miraclegarden.smsmessage.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.miraclegarden.smsmessage.Activity.NotificationActivity;
import com.miraclegarden.smsmessage.App;
import com.miraclegarden.smsmessage.MessageInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NotificationService extends NotificationListenerService {
    private static final String TAG = "NotificationService";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationActivity.sendMessage("监听服务成功!");
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        getSbnByNotificatinList(sbn);

    }

    public void getSbnByNotificatinList(StatusBarNotification sbn) {
        MessageInfo messageInfo = App.getMessageByNotiList(this, sbn.getPackageName());
        if (messageInfo != null) {
            initData(messageInfo, sbn);
        }
    }

    private String text = "";

    private void initData(MessageInfo messageInfo, StatusBarNotification sbn) {
        Bundle bundle = sbn.getNotification().extras;
        String title = bundle.getString(Notification.EXTRA_TITLE, "获取标题失败!");
        String context = bundle.getString(Notification.EXTRA_TEXT, "获取内容失败!");
        if (context.equals("获取内容失败!")) {
            if (sbn.getNotification().tickerText != null) {
                context = sbn.getNotification().tickerText.toString();
            }
        }
        NotificationActivity.sendMessage(title + " " + context);
        if (!text.equals(context)) {
            if (!title.equals("获取标题失败!") && !context.equals("获取内容失败!") && !title.contains("正在运行")) {
                NotificationActivity.sendMessage("准备发送服务器:成功");
                Submit(messageInfo,title, context);
            }
        }
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public void Submit(MessageInfo messageInfo,String title, String context) {
        OkHttpClient client = new OkHttpClient();
        SharedPreferences sharedPreferences = getSharedPreferences("server", MODE_PRIVATE);
        try {

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", messageInfo.getName());
            jsonObject.put("code", messageInfo.getCode());
            jsonObject.put("remark", messageInfo.getRemark());
            jsonObject.put("appName", messageInfo.getAppName());
            jsonObject.put("packageName", messageInfo.getPackageName());

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("title", title+System.currentTimeMillis());
            jsonObject1.put("context", context+System.currentTimeMillis());
            jsonObject.put("data", jsonObject1);

            String json = jsonObject.toString();

            RequestBody body = RequestBody.create(json, JSON);

            // 构建请求
            Request request = new Request.Builder()
                    .url(sharedPreferences.getString("host", ""))
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    NotificationActivity.sendMessage("提交失败:" + e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String str = response.body().string();
                        NotificationActivity.sendMessage(title + "提交成功:" + str);
                        text = context;
                        return;
                    }
                    NotificationActivity.sendMessage("提交失败:");
                }
            });
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听断开
     */
    @Override
    public void onListenerDisconnected() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 通知侦听器断开连接 - 请求重新绑定
            requestRebind(new ComponentName(this, NotificationListenerService.class));
        }
    }

    /**
     * @param context 反正第二次启动失败
     */
    public static void toggleNotificationListenerService(Context context) {
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(context, NotificationService.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(new ComponentName(context, NotificationService.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }

}
