package com.miraclegarden.smsmessage.network;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.miraclegarden.smsmessage.AppConfig;
import com.miraclegarden.smsmessage.MessageInfo;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

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

/**
 * 将抓取到的消息转发到 PC 本地调试服务，便于浏览器查看。
 */
public final class DebugForwarder {

    private static final String TAG = "DebugForwarder";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();

    private DebugForwarder() {
    }

    public static void forward(Context context, MessageInfo messageInfo,
                               String title, String content, long timestamp, String source) {
        forward(context, messageInfo, title, content, timestamp, source, null);
    }

    public static void forward(Context context, MessageInfo messageInfo,
                               String title, String content, long timestamp, String source,
                               Runnable onComplete) {
        if (!AppConfig.ENABLE_DEBUG_FORWARD || messageInfo == null) {
            if (onComplete != null) {
                onComplete.run();
            }
            return;
        }

        try {
            JSONObject json = new JSONObject();
            json.put("source", source != null ? source : "unknown");
            json.put("packageName", messageInfo.getPackageName());
            json.put("appName", messageInfo.getAppName());
            json.put("title", title != null ? title : "");
            json.put("group", resolveGroup(title, messageInfo));
            json.put("content", content != null ? content : "");
            json.put("timestamp", timestamp);

            Request request = new Request.Builder()
                    .url(AppConfig.DEBUG_SERVER_URL + "/api/debug/push")
                    .header("Content-Type", "application/json")
                    .post(RequestBody.create(json.toString(), JSON))
                    .build();

            Log.d(TAG, "forwarding [" + source + "] " + messageInfo.getPackageName()
                    + " -> " + AppConfig.DEBUG_SERVER_URL);

            CLIENT.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, java.io.IOException e) {
                    Log.w(TAG, "forward failed [" + source + "]: " + e.getMessage());
                    if (onComplete != null) {
                        onComplete.run();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) {
                    int code = response.code();
                    response.close();
                    if (code >= 200 && code < 300) {
                        Log.d(TAG, "forward ok [" + source + "] " + title);
                    } else {
                        Log.w(TAG, "forward http " + code + " [" + source + "] " + title);
                    }
                    if (onComplete != null) {
                        onComplete.run();
                    }
                }
            });
        } catch (Exception e) {
            Log.w(TAG, "forward build failed: " + e.getMessage());
            if (onComplete != null) {
                onComplete.run();
            }
        }
    }

    private static String resolveGroup(String title, MessageInfo messageInfo) {
        if (!TextUtils.isEmpty(title)) {
            return title.trim();
        }
        if (messageInfo != null && !TextUtils.isEmpty(messageInfo.getAppName())) {
            return messageInfo.getAppName();
        }
        return "未分类";
    }
}
