package com.rnwalletman;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * SMS 广播接收器
 */
public class SmsReceiver extends BroadcastReceiver {
    private static final String TAG = "RNWalletSmsReceiver";
    
    @Override
    public void onReceive(Context context, Intent intent) {
        // 检查是否启用监听
        SharedPreferences prefs = context.getSharedPreferences("rnwalletman", Context.MODE_PRIVATE);
        boolean isEnabled = prefs.getBoolean("sms_enabled", false);
        
        if (!isEnabled) {
            return;
        }
        
        if ("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                if (pdus != null) {
                    for (Object pdu : pdus) {
                        SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
                        String sender = sms.getDisplayOriginatingAddress();
                        String message = sms.getMessageBody();
                        long timestamp = sms.getTimestampMillis();
                        
                        Log.i(TAG, "收到短信: " + sender + " - " + message);
                        
                        // 发送事件到 React Native
                        SmsNotificationModule.sendSmsEvent(sender, message, timestamp);
                    }
                }
            }
        }
    }
}
