package cn.sunner.sms2calendar;

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

import java.lang.reflect.InvocationTargetException;

public class SMSReceiver extends BroadcastReceiver {
    private String TAG = "SMS2Cal";

    public SMSReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // Get the data (SMS data) bound to intent
        Bundle bundle = intent.getExtras();

        SmsMessage[] msgs = null;

        String str = "";

        if (bundle != null) {
            // Retrieve the SMS Messages received
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];

            // For every SMS message received
            for (int i=0; i < msgs.length; i++) {
                // Convert Object array
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                SMSParser parser = getParser(msgs[i].getOriginatingAddress(), msgs[i].getMessageBody());
                if (parser != null && parser.isValid()) {
                    Notification.add(context, parser);
                }
            }
        }
    }

    protected static SMSParser getParser(String fromNumber, String text) {
        try {
            Class <?> cls = Class.forName("cn.sunner.sms2calendar.N" + fromNumber + "Parser");
            return (SMSParser) cls.getDeclaredConstructor(String.class).newInstance(text);
        } catch (ClassNotFoundException e) {
            // Do nothing. Not all phone number has a parser class
        } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

@@ -606,34 +606,8 @@
 l;%0A%0A
-        String str = %22%22;%0A%0A
     
@@ -809,11 +809,15 @@
  // 
-For
+Combine
  eve
@@ -831,32 +831,96 @@
 message received
+. big SMS may be separated.%0A            String messageBody = %22%22;
 %0A            for
@@ -926,17 +926,19 @@
 r (int i
-=
+ = 
 0; i %3C m
@@ -1066,24 +1066,92 @@
 us%5Bi%5D);%0A    
+            messageBody += msgs%5Bi%5D.getMessageBody();%0A            %7D%0A%0A
             
@@ -1180,25 +1180,25 @@
 Parser(msgs%5B
-i
+0
 %5D.getOrigina
@@ -1213,27 +1213,16 @@
 ess(), m
-sgs%5Bi%5D.getM
 essageBo
@@ -1227,17 +1227,11 @@
 Body
-()
 );%0A
-    
     
@@ -1296,20 +1296,16 @@
         
-    
 Notifica
@@ -1335,26 +1335,8 @@
 r);%0A
-                %7D%0A
     

support big SMS message