package ir.gemacc.admin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (context == null || intent == null || !Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) return;
        SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
        if (messages == null || messages.length == 0) return;

        StringBuilder body = new StringBuilder();
        String sender = "";
        long receivedAt = System.currentTimeMillis();
        for (SmsMessage message : messages) {
            if (message == null) continue;
            if (sender.length() == 0 && message.getOriginatingAddress() != null) sender = message.getOriginatingAddress();
            if (message.getMessageBody() != null) body.append(message.getMessageBody());
            if (message.getTimestampMillis() > 0) receivedAt = message.getTimestampMillis();
        }
        String fullBody = body.toString();
        if (!SmsUploader.looksLikeDepositSms(fullBody)) return;

        Context app = context.getApplicationContext();
        SmsUploader.noteIncomingSms(app, sender);
        SmsUploader.enqueueSms(app, sender, fullBody, receivedAt, false);
        SmsUploader.scheduleImmediate(app);

        PendingResult pendingResult = goAsync();
        new Thread(() -> {
            try { SmsUploader.processQueueBlocking(app); }
            finally { try { pendingResult.finish(); } catch (Exception ignored) {} }
        }).start();
    }
}
