/*
  * Metoda koja nadodaje dolaznu poruku u list view.
  * */
 public static void AddIncomingMessageToView(string smsSender,string smsBody,string smsTime,string smsTimePaying,string smsDate)
 {
     Pay_SMS_Main psm=new Pay_SMS_Main();
     //			Log.Debug ("time",smsTime);
     //			Log.Debug ("body",smsBody);
     //			Log.Debug ("date",smsDate);
     //			Log.Debug ("sender",smsSender);
     //			Log.Debug ("time paying",smsTimePaying);
     string poruka = psm.MessageDisplayIncoming (smsSender, smsBody,smsTime,smsTimePaying,smsDate);
     //			Log.Debug ("time",smsTime);
     //			Log.Debug ("body",smsBody);
     //			Log.Debug ("date",smsDate);
     //			Log.Debug ("sender",smsSender);
     //			Log.Debug ("time paying",smsTimePaying);
     //string poruka=psm.DetermineZone(smsSender)+" [ " +smsBody +" ]" + " "+smsTime;
     //zapisuje poruku u datoteku
     using (StreamWriter sw = File.AppendText (psm.message_Data)) { //psm.message_Data
         sw.Write (poruka+"\n");
     };
 }
        /*
         * Metoda koje reagira na dolaznu poruku.
         * Sprema sadrzaj u poruka i preko delegata ReceiveSMSdelegate poruka se koristi dalje.
         * */
        public override void OnReceive(Context context, Intent intent)
        {
            Log.Info ("SmsReceiver", "SMS Received");

            if (intent.Action == INTENT_ACTION) {

                StringBuilder buffer = new StringBuilder ();
                Bundle bundle = intent.Extras;
                String smsSender = "";
                String smsBody = "";
                String smsTime = "";
                String[] smsTimePaying = new string[5];
                String smsDate = "";
                bool valid_body_check = false;
                String smsFilteredBody = "";

                if (bundle != null) {
                    Java.Lang.Object[] pdus = (Java.Lang.Object[])bundle.Get ("pdus");

                    Pay_SMS_Main psm = new Pay_SMS_Main ();
                    SmsMessage[] msgs;

                    msgs = new SmsMessage[pdus.Length];
                    try {
                        for (int i = 0; i < msgs.Length; i++) {	//obradujem poruku
                            msgs [i] = SmsMessage.CreateFromPdu ((byte[])pdus [i]);
                            smsSender = msgs [i].OriginatingAddress;
                            smsBody = msgs [i].MessageBody;

                            String smsTimeH=DateTime.UtcNow.Hour.ToString ();
                            String smsTimeM=DateTime.UtcNow.Minute.ToString ();
                            smsTime=smsTimeH+":"+smsTimeM;
                            String time=smsTime.ToString ();

                            try {
                                var tuple = ParseSMS.ParseSMSbody (smsBody);
                                valid_body_check = tuple.Item1; //bool true or false
                                smsFilteredBody = tuple.Item2; // car registration
                                smsTimePaying=tuple.Item3.Split ('.');
                            } catch (Exception e) {
                                Log.Debug ("Greska prilikom filtriranja sms poruke.", e.ToString ());
                            }

                            try{
                             smsDate = DateTime.Now.ToString ("d.M.yyyy");
                            }catch(Exception){
                                Log.Debug ("Krivo konvertiranje datuma","smsDate");
                            }
            //
            //						Log.Debug ("sender",smsSender);
            //						Log.Debug ("evaluation",(smsSender != null).ToString ());
            //						Log.Debug ("number",psm.CheckSMSNumbers (smsSender).ToString ());
            //						Log.Debug ("check",valid_body_check.ToString ());

                            if ((smsSender != null) && psm.CheckSMSNumbers (smsSender) && valid_body_check) {
                                //send sms data to further reproduction

                    try{

                                    Pay_SMS_Main.AddIncomingMessageToView (smsSender, smsFilteredBody, time,smsTimePaying[0], smsDate);
                    }catch(Exception e){
                                    Log.Debug ("Krivo ucitavanje AddIncomingMessageToView... ",e.ToString ());
                                }
                } else {
                    Log.Debug ("SMS was not from parking number!", "Pass message.");

                }
            }
            } catch (Exception e) {

            Log.Debug ("Exception caught while receiving message: !!!", e.Message);
            }
            }

            }
        }
        /*
         * Fill list with message data from user Inbox.
         * */
        public static void Fill_With_Inbox_Data(Activity context,ListView listView)
        {
            Pay_SMS_Main psm=new Pay_SMS_Main();

                update_inbox_messages = true;
                List<String> items=new List<String>();
                bool valid_body_check=false;
                String smsFilteredBody="";
                String[] smsTimePaying= new string[5];

                String[] projection = new String[]{ "address", "body","date" };
                CursorLoader loader=new CursorLoader(context);
                try{
                    //slaže podatke obrnutim redom,tj od najstarijeg do najmlađeg tako da kad dodajem novi podatak na kraj da bude poredano
                    loader = new CursorLoader( context,Android.Net.Uri.Parse ("content://sms/inbox"), projection, null, null, null);
                }catch(Exception e){
                    Log.Debug ("Problem kod loadera",e.ToString ());
                }
                ICursor  cursor =  (ICursor)loader.LoadInBackground ();

                if (cursor.MoveToFirst ()) { // must check the result to prevent exception
                    do {
                        try {
                            //Ako je broj iz datoteke Zone_Numbers_Assets, odnosno ako je broj iz raspona dozvoljenih
                            if (psm.CheckSMSNumbers(cursor.GetString (cursor.GetColumnIndexOrThrow (projection [0]))))
                            {
                                String smsSender = cursor.GetString (cursor.GetColumnIndexOrThrow (projection [0]));
                                String smsBody = cursor.GetString (cursor.GetColumnIndexOrThrow (projection [1]));
                                String smsTime = cursor.GetString (cursor.GetColumnIndexOrThrow (projection [2]));
                                long smsTimeLong=long.Parse (smsTime);
                                String smsDate=psm.ConvertDateFromMillseconds (smsTimeLong);
                                smsTime=psm.ConvertTimeFromMillseconds (smsTimeLong);

                            try{
                                var tuple=ParseSMS.ParseSMSbody (smsBody);
                                valid_body_check = tuple.Item1; //bool true or false
                                smsFilteredBody = tuple.Item2; // car registration
                                smsTimePaying=tuple.Item3.Split ('.');// car_time
                            }catch(Exception e){
                                Log.Debug ("Greska prilikom filtriranja sms poruke.",e.ToString ());
                            }
                            //check if sms body pass validation
                            if(valid_body_check){
                                String msgData = psm.MessageDisplay (smsSender, smsFilteredBody,smsTime,smsTimePaying[0],smsDate);
                                items.Add (msgData);
                            }

                            }
                        } catch (Exception e) {
                            Log.Debug ("UCITAVANJE SMS-a u Pay_SMS_Main", e.ToString ());
                        }
                    } while (cursor.MoveToNext ());
                } else { // empty box, no SMS
                    cursor.Close ();
                }
                //okrecem podatke u descending nacin,tako da je najnoviji podatak na pocetku
                items.Reverse ();
                DeleteHistory ();
                using(StreamWriter writer = new StreamWriter(message_Data)){

                    foreach(String data in items ){
                        writer.Write (data+"\n");
                    };
                }

                try{
                    FillListWithData(items,context,listView);
                }catch(NullReferenceException e){
                    Log.Debug ("FillListWithData:U ucitavanju inboxa",	e.ToString ());
                    }

                Enable_message_update=false;
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.Pay_Automat_Main_Enter);

            text_time_screen = FindViewById<EditText> (Resource.Id.edit_time_automat);
            btn_save_time = FindViewById<Button> (Resource.Id.btn_save_time);
            btn_change_time = FindViewById<Button> (Resource.Id.btn_change_time);

            listView = FindViewById<ListView> (Resource.Id.List_SMS_Main_History);

            spinnerPayA = FindViewById<Spinner> (Resource.Id.zoneSpinner);
            spinnerList = FillSpinnerWithData ();

            ArrayAdapter<string> spinnerArrayAdapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleSpinnerItem, spinnerList);
            spinnerArrayAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinnerPayA.Adapter = spinnerArrayAdapter;

            #region PuniListu
            //Log.Debug ("ON CREATE","DULJINA"+new FileInfo(message_Data).Length+" -- "+Enable_message_update);
            long duljina = 0;
            try {
                duljina = new FileInfo (message_Data).Length;
            } catch (Exception e) {

                Log.Debug ("Pay_SMS_Main", "FILE INFO krivo učitava " + e.ToString ());
            }
            Pay_SMS_Main psm = new Pay_SMS_Main ();

            if (duljina != 0 || Fill_ListView_With_Data.update_inbox_messages == true) {
                List<string> data = new List<string> ();
                String line;

                StreamReader reader = new StreamReader (message_Data);
                while ((line = reader.ReadLine ()) != null) {
                    data.Add (line);
                }
                reader.Close ();
                podaciDialogLista = data;
                try {
                    Fill_ListView_With_Data.FillListWithData (data, this, listView);
                } catch (NullReferenceException e) {
                    Log.Debug ("Fill_ListView_With_Data.FillListWithData",	e.ToString ());
                }
            } else {
                Fill_ListView_With_Data.DeleteHistory ();
            }

            //if user enabled Inbox messages
            if (Fill_ListView_With_Data.Enable_message_update == true) {
                Fill_ListView_With_Data.Fill_With_Inbox_Data (this, listView);
            }

            #endregion

            listView.ItemClick += OnListItemClick;

            UpdateTime ();
            UpdateDisplay ();

            TimePickerDialog time_dialog = new TimePickerDialog (this, TimePickerCallback, hour, minute, true);

            //Prikazuje trenutno vrijeme i nudi odabir promjene ili prekid.
            btn_change_time.Click += delegate {
                UpdateTime ();
                time_dialog = new TimePickerDialog (this, TimePickerCallback, hour, minute, true);
                time_dialog.Show ();
            };

            /*
             * UPALI ALARM I SPREMI VRIJEME PLACANJA U HISTORY
             * */
            btn_save_time.Click += delegate {
                var prefs = Application.Context.GetSharedPreferences ("MySharedPrefs", FileCreationMode.Private);
                var valid_Alarm=prefs.GetBoolean ("MyAlarmValue", true);

                if (valid_Alarm) {
                    Toast.MakeText (this,"Alarm JE upaljen",ToastLength.Short).Show();
                    ActivatedAlarmOnSMS ();
                }else{
                    Toast.MakeText (this,"Alarm NIJE upaljen",ToastLength.Short).Show ();
                    var activity_pay_main=new Intent (this,typeof(Pay_Main));
                    StartActivity (activity_pay_main);
                }
            };
        }