package com.xypower.mpmaster.sms;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 短信接收的监听的广播
 *
 * @author jingjing
 */
public class SmsReceiver extends BroadcastReceiver {

    public static final String SMS_BUNDLE = "pdus";
    public static long mLastSmsTime = System.currentTimeMillis();
    private static final SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onReceive(Context context, Intent intent) {
        try {

            if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
                SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
                for (SmsMessage smsMessage : smsMessages) {

                    // Log.i("SMS", "RECV " + mSimpleDateFormat.format(dt) + " " + smsMessage.getMessageBody());

                    if (smsMessage.getTimestampMillis() < mLastSmsTime) {

                        Date dt = new Date(smsMessage.getTimestampMillis());
                        Log.i("SMS", "MSG @" + mSimpleDateFormat.format(dt) + " Dropped: " + smsMessage.getMessageBody());
                        SimUtil.setSmsMessageRead(context, smsMessage);
                        continue;
                    }

                    mLastSmsTime = smsMessage.getTimestampMillis();
                    SimUtil.analysisSMSInfo(context, intent, smsMessage);

                    // SimUtil.setSmsMessageRead(context, smsMessage);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


}