package oko.tm.oko_pro_classic;



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver
{
    public final static String SMS_BROADCAST_TO_START_ACTION = "oko.tm.oko_pro_classic.smsreceiverbackbroadcasttostart";

    public static volatile boolean StartActivity_Started=false;

    public static int PHONE_NUMBER_TAIL=8;
    Context mContext;


    @Override
    public void onReceive(Context context, Intent intent)
    {
        mContext=context;

        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "", message_from="", message_text="", phone1="", phone2="";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++)
            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                message_from += msgs[i].getOriginatingAddress();
                message_text += msgs[i].getMessageBody().toString();
                str += "SMS \u2193\n" + msgs[i].getOriginatingAddress();
                str += " :\n";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
            }



            //check all phones
            boolean exist_phone=false;
            try {
                SharedPreferences tempSettings;
                for (int i=0; i< StartActivity.objectsSettings.length; i++){
                    tempSettings= mContext.getSharedPreferences(StartActivity.objectsSettings[i], Context.MODE_PRIVATE);
                    String ph="";
                    if (tempSettings.contains(MainActivity.APP_PREFERENCES_PHONE)) {
                        ph = tempSettings.getString(MainActivity.APP_PREFERENCES_PHONE, "");
                    }
                    phone1=ph;
                    phone2=message_from;
                    // ----- сравниеваем номер входной смс с номером прибора - сравниваем "хвост"
                    if (phone1.length()>PHONE_NUMBER_TAIL) {
                        phone1=phone1.substring(phone1.length()-PHONE_NUMBER_TAIL).toString();
                    }

                    if (phone2.length()>PHONE_NUMBER_TAIL) {
                        phone2 = phone2.substring(phone2.length() - PHONE_NUMBER_TAIL);
                    }

                    if (phone1.equals(phone2)) {
                        exist_phone=true;
                        break;
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }


            if (exist_phone) //phone1.equals(phone2)
            {

                //---display the new SMS message---
                Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

                if (!StartActivity_Started) {

                    //--- перезапускаем приложение
                    Intent startActivity = new Intent();
                    startActivity.setClass(context, StartActivity.class);
                    startActivity.setAction(StartActivity.class.getName());
                    startActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    startActivity.putExtra("message", message_text);
                    startActivity.putExtra("sender", message_from);
                    context.startActivity(startActivity);

                }
                else {

                    //передаем данные в приемник
                    try {
                        Intent intent1 = new Intent(SMS_BROADCAST_TO_START_ACTION);
                        intent1.putExtra("message", message_text);
                        intent1.putExtra("sender", message_from);
                        //context.sendBroadcast(intent1);
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


            }
        }
    }
}
