package oko.tm.oko_pro_classic;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import java.util.HashSet;
import java.util.Set;

import static android.R.attr.button;
import static oko.tm.oko_pro_classic.R.string.app_name;
import static oko.tm.oko_pro_classic.R.string.object_1;
import static oko.tm.oko_pro_classic.R.string.object_2;
import static oko.tm.oko_pro_classic.R.string.object_3;
import static oko.tm.oko_pro_classic.R.string.object_4;
import static oko.tm.oko_pro_classic.R.string.object_5;
import static oko.tm.oko_pro_classic.R.string.object_6;
import static oko.tm.oko_pro_classic.R.string.object_7;
import static oko.tm.oko_pro_classic.R.string.object_8;
import static oko.tm.oko_pro_classic.R.string.object_9;
import static oko.tm.oko_pro_classic.R.string.object_10;
import static oko.tm.oko_pro_classic.R.string.object_list;
import static oko.tm.oko_pro_classic.SmsReceiver.PHONE_NUMBER_TAIL;

public class StartActivity extends AppCompatActivity { //ActionBarActivity
    Context mContext;
    public static volatile boolean MainActivity_Started=false;
    public static final  String TCP_BROADCAST_TO_MAIN_ACTION = "oko.tm.oko_pro_classic.broadcasttomain";
    public final static String SMS_BROADCAST_TO_MAIN_ACTION = "oko.tm.oko_pro_classic.smsbroadcasttomain";
    //----- для создания служебного лога
    private static final String TAG = "myLogs";
    private final String server_url = "http://ok.webhop.net/update/monitor/";
    private static final int PERMISSIONS_REQUEST_SMS = 2;
    private static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE= 5469;

    public static String START_PREFERENCES = "oko_pro_classic_settings_main";
    public static String START_PREFERENCES_OBJECT1 = "object_name1";
    public static String START_PREFERENCES_OBJECT2 = "object_name2";
    public static String START_PREFERENCES_OBJECT3 = "object_name3";
    public static String START_PREFERENCES_OBJECT4 = "object_name4";
    public static String START_PREFERENCES_OBJECT5 = "object_name5";
    public static String START_PREFERENCES_OBJECT6 = "object_name6";
    public static String START_PREFERENCES_OBJECT7 = "object_name7";
    public static String START_PREFERENCES_OBJECT8 = "object_name8";
    public static String START_PREFERENCES_OBJECT9 = "object_name9";
    public static String START_PREFERENCES_OBJECT10 = "object_name10";
    public static String START_PREFERENCES_CURRENTOBJECT = "current_object";
    public static String START_PREFERENCES_APPPASSWORD = "app_password";
    public static String START_PREFERENCES_RESTORELASTOBJECT = "restore_last_object";

    public static final String[] objectsSettings = {"oko_pro_classic_settings",
                                                        "oko_pro_classic_settings2",
                                                        "oko_pro_classic_settings3",
                                                        "oko_pro_classic_settings4",
                                                        "oko_pro_classic_settings5",
                                                        "oko_pro_classic_settings6",
                                                        "oko_pro_classic_settings7",
                                                        "oko_pro_classic_settings8",
                                                        "oko_pro_classic_settings9",
                                                        "oko_pro_classic_settings10"};

    public static final String OBJECT_NAME = "oko.tm.oko_pro_classic.OBJECT_NAME";
    public static final String OBJECT_SETTING = "oko.tm.oko_pro_classic.OBJECT_SETTING";
    Button button_object1;
    Button button_object2;
    Button button_object3;
    Button button_object4;
    Button button_object5;
    Button button_object6;
    Button button_object7;
    Button button_object8;
    Button button_object9;
    Button button_object10;


    // переменная для работы с файлом
    SharedPreferences mSettings;

    //для широковещательного приемника, настроенного на прием данных с сервиса
    BroadcastReceiver br_tcp;
    BroadcastReceiver br_sms;

    public static volatile int current_object=0;

    public static volatile boolean need_check_password=true;

    public static volatile boolean start_done=false;


    @Override
    public boolean onSupportNavigateUp() {
        finish(); // close this activity as oppose to navigating up

        return false;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        mContext=this;

        Log.d(TAG, "StartActivity onCreate");

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        try {
            ClientThread.StartActivity_Started = false;
            SmsReceiver.StartActivity_Started = false;
        }catch (Exception e) {
            e.printStackTrace();
        }

        final Intent intent = getIntent();

        // Possible work around for market launches. See http://code.google.com/p/android/issues/detail?id=2373
        // for more details. Essentially, the market launches the main activity on top of other activities.
        // we never want this to happen. Instead, we check if we are the root and if not, we finish.
        if (!isTaskRoot()) {
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(intent.getAction())) {
                Log.d(TAG, "Start Activity is not the root.  Finishing Start Activity instead of launching.");
                finish();
                return;
            }
        }


        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_launcher); //R.drawable.ic_launcher

        //getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        //getSupportActionBar().setCustomView(R.layout.activity_title);
        setTitle(object_list);

        mSettings= getSharedPreferences(START_PREFERENCES, Context.MODE_PRIVATE);

        // создаем BroadcastReceiver для приема данных с сервиса
        br_tcp = new BroadcastReceiver() {
            // действия при получении сообщений
            public void onReceive(Context context, Intent intent) {

                String type = intent.getStringExtra(ClientThread.PARAM_TYPE);
                String data = intent.getStringExtra(ClientThread.PARAM_DATA);
                int object_num = intent.getIntExtra(ClientThread.PARAM_OBJECT, 0);

                // Ловим сообщения о наличии связи
                if (ClientThread.STATUS_CONNECTION.equals(type)) {
                    try {
                        Intent intent1 = new Intent(TCP_BROADCAST_TO_MAIN_ACTION);
                        intent1.putExtra(ClientThread.PARAM_TYPE, ClientThread.STATUS_CONNECTION);
                        intent1.putExtra(ClientThread.PARAM_DATA, data);
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                if (ClientThread.SYSTEM_DATA.equals(type) && object_num>0) {
                    try {
                        //check mainactivity state
                        if ( current_object==object_num) {
                            Log.d(TAG, "Resend system data by localbroadcast to current MainActivity, object = " + current_object);
                            //передаем данные в MainActivity throw local broadcast
                            try {
                                Intent intent2 = new Intent(TCP_BROADCAST_TO_MAIN_ACTION);
                                intent2.putExtra(ClientThread.PARAM_TYPE, ClientThread.SYSTEM_DATA);
                                intent2.putExtra(ClientThread.PARAM_DATA, data);
                                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent2);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                                try {
                                    if (current_object > 0) finishActivity(current_object);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                start_done=true;
                                MainActivity_Started = false;
                                current_object = object_num;
                                save_current_object(current_object);
                                Log.d(TAG, "Try relaunch MainActivity, object = " + current_object);

                                try {

                                    Intent intent1 = new Intent(mContext, MainActivity.class);

                                    int i= object_num -1;
                                    String obj="";
                                    if (i == 0)
                                        obj = button_object1.getText().toString();
                                    if (i == 1)
                                        obj = button_object2.getText().toString();
                                    if (i == 2)
                                        obj = button_object3.getText().toString();
                                    if (i == 3)
                                        obj = button_object4.getText().toString();
                                    if (i == 4)
                                        obj = button_object5.getText().toString();
                                    if (i == 5)
                                        obj = button_object6.getText().toString();
                                    if (i == 6)
                                        obj = button_object7.getText().toString();
                                    if (i == 7)
                                        obj = button_object8.getText().toString();
                                    if (i == 8)
                                        obj = button_object9.getText().toString();
                                    if (i == 9)
                                        obj = button_object10.getText().toString();

                                    intent1.putExtra(OBJECT_NAME, obj);
                                    intent1.putExtra(OBJECT_SETTING, objectsSettings[i]);
                                    intent1.putExtra(ClientThread.PARAM_TYPE, ClientThread.SYSTEM_DATA);
                                    intent1.putExtra(ClientThread.PARAM_DATA, data);
                                    //intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY );
                                    //startActivity(intent1);
                                    startActivityForResult(intent1,current_object);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // Ловим сообщения от прибора
                if (ClientThread.DEVICE_DATA.equals(type)) {
                    //find object name by IMEI
                    String imei="-1";
                    int event=-1;

                    //Toast.makeText(mContext, data, Toast.LENGTH_LONG).show();

                    try {
                        String[] requestParts = data.split(","); //data packet
                        imei=requestParts[0].substring(1);
                        event=hex2decimal(requestParts[1]);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }



                    try {
                        SharedPreferences tempSettings;
                        for (int i=0; i< objectsSettings.length; i++)
                        {
                            tempSettings= mContext.getSharedPreferences(objectsSettings[i], Context.MODE_PRIVATE);
                            String tt="";
                            if (tempSettings.contains(MainActivity.APP_PREFERENCES_IMEI)) {
                                tt = tempSettings.getString(MainActivity.APP_PREFERENCES_IMEI, "");
                            }

                            if (tt.equals(imei)) {
                                Log.d(TAG, "StartActivity onReceive: imei=" + imei + ", object=" + (i+1) + ", curr_obj=" +current_object);
                                //check if  event needs notification
                                boolean notification_event=false;
                                if (
                                        (event>=0 && event<=15)
                                        || (event>=20 && event<=39)
                                                || (event>=42 && event<=49)
                                                || (event>=58 && event<=61)
                                                || (event>=64 && event<=215)
                                                || (event>=235 && event<=238)
                                                || (event>=250 && event<=250)
                                                || (event>=255 && event<=255)
                                                || (event>=350 && event<=437)
                                                || (event>=454 && event<=581)
                                                || (event>=646 && event<=694)
                                                || (event>=720 && event<=751)

                                        )
                                notification_event=true;

                                if (notification_event || (current_object==(i+1))){
                                    //check mainactivity state
                                    if ( current_object==(i+1)) {
                                        Log.d(TAG, "Resend data by localbroadcast to current MainActivity, object = " + current_object);
                                        //передаем данные в MainActivity throw local broadcast
                                        try {
                                            Intent intent2 = new Intent(TCP_BROADCAST_TO_MAIN_ACTION);
                                            intent2.putExtra(ClientThread.PARAM_TYPE, ClientThread.DEVICE_DATA);
                                            intent2.putExtra(ClientThread.PARAM_DATA, data);
                                            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent2);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    else
                                    {
                                        if (notification_event) {

                                            try {
                                                if (current_object > 0) finishActivity(current_object);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            start_done=true;
                                            MainActivity_Started = false;
                                            current_object = i + 1;
                                            save_current_object(current_object);
                                            Log.d(TAG, "Try relaunch MainActivity, object = " + current_object);

                                            try {

                                                Intent intent1 = new Intent(mContext, MainActivity.class);

                                                String obj = "";
                                                if (i == 0)
                                                    obj = button_object1.getText().toString();
                                                if (i == 1)
                                                    obj = button_object2.getText().toString();
                                                if (i == 2)
                                                    obj = button_object3.getText().toString();
                                                if (i == 3)
                                                    obj = button_object4.getText().toString();
                                                if (i == 4)
                                                    obj = button_object5.getText().toString();
                                                if (i == 5)
                                                    obj = button_object6.getText().toString();
                                                if (i == 6)
                                                    obj = button_object7.getText().toString();
                                                if (i == 7)
                                                    obj = button_object8.getText().toString();
                                                if (i == 8)
                                                    obj = button_object9.getText().toString();
                                                if (i == 9)
                                                    obj = button_object10.getText().toString();

                                                intent1.putExtra(OBJECT_NAME, obj);
                                                intent1.putExtra(OBJECT_SETTING, objectsSettings[i]);
                                                intent1.putExtra(ClientThread.PARAM_TYPE, ClientThread.DEVICE_DATA);
                                                intent1.putExtra(ClientThread.PARAM_DATA, data);
                                                //intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY );
                                                //startActivity(intent1);
                                                startActivityForResult(intent1,current_object);

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }

                                    }

                                }

                                break;
                            }
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }

                }

            }
        };
        // создаем фильтр для BroadcastReceiver
        IntentFilter intFilt = new IntentFilter(ClientThread.TCP_BROADCAST_TO_START_ACTION);
        // регистрируем (включаем) BroadcastReceiver
        LocalBroadcastManager.getInstance(mContext).registerReceiver(br_tcp, intFilt);


        // создаем BroadcastReceiver для приема данных с sms_receiver (вариант через broadcast)
        br_sms = new BroadcastReceiver() {
            // действия при получении сообщений
            public void onReceive(Context context, Intent intent) {

                String message_text = intent.getStringExtra("message");
                String sender = intent.getStringExtra("sender");
                Log.d(TAG, "StartActivity SMS_onReceive: sender = " + sender + ", message = " + message_text);
                sms_resend(message_text, sender);
            }
        };
        // создаем фильтр для BroadcastReceiver
        IntentFilter intFilt_sms = new IntentFilter(SmsReceiver.SMS_BROADCAST_TO_START_ACTION);
        LocalBroadcastManager.getInstance(mContext).registerReceiver(br_sms, intFilt_sms);

        checkPermission();

        button_object1 = (Button) findViewById(R.id.button_object1);
        button_object2 = (Button) findViewById(R.id.button_object2);
        button_object3 = (Button) findViewById(R.id.button_object3);
        button_object4 = (Button) findViewById(R.id.button_object4);
        button_object5 = (Button) findViewById(R.id.button_object5);
        button_object6 = (Button) findViewById(R.id.button_object6);
        button_object7 = (Button) findViewById(R.id.button_object7);
        button_object8 = (Button) findViewById(R.id.button_object8);
        button_object9 = (Button) findViewById(R.id.button_object9);
        button_object10 = (Button) findViewById(R.id.button_object10);


        addListenerOnButtonObject1();
        addListenerOnButtonObject2();
        addListenerOnButtonObject3();
        addListenerOnButtonObject4();
        addListenerOnButtonObject5();
        addListenerOnButtonObject6();
        addListenerOnButtonObject7();
        addListenerOnButtonObject8();
        addListenerOnButtonObject9();
        addListenerOnButtonObject10();

        //-------------
        //обратотка входящей смс от SmsReceiver
        String message_text = intent.getStringExtra("message");
        String sender = intent.getStringExtra("sender");
        sms_resend(message_text, sender);
        //--------------------------------

    }



    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.d(TAG, "StartActivity onResume");
        try {
            current_object = 0;

            if (mSettings.contains(START_PREFERENCES_OBJECT1)) {
                button_object1.setText(mSettings.getString(START_PREFERENCES_OBJECT1, String.valueOf(object_1)));
                if (button_object1.getText().equals("")) button_object1.setVisibility(View.INVISIBLE); else button_object1.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT2)) {
                button_object2.setText(mSettings.getString(START_PREFERENCES_OBJECT2, String.valueOf(object_2)));
                if (button_object2.getText().equals("")) button_object2.setVisibility(View.INVISIBLE); else button_object2.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT3)) {
                button_object3.setText(mSettings.getString(START_PREFERENCES_OBJECT3, String.valueOf(object_3)));
                if (button_object3.getText().equals("")) button_object3.setVisibility(View.INVISIBLE); else button_object3.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT4)) {
                button_object4.setText(mSettings.getString(START_PREFERENCES_OBJECT4, String.valueOf(object_4)));
                if (button_object4.getText().equals("")) button_object4.setVisibility(View.INVISIBLE); else button_object4.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT5)) {
                button_object5.setText(mSettings.getString(START_PREFERENCES_OBJECT5, String.valueOf(object_5)));
                if (button_object5.getText().equals("")) button_object5.setVisibility(View.INVISIBLE); else button_object5.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT6)) {
                button_object6.setText(mSettings.getString(START_PREFERENCES_OBJECT6, String.valueOf(object_6)));
                if (button_object6.getText().equals("")) button_object6.setVisibility(View.INVISIBLE); else button_object6.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT7)) {
                button_object7.setText(mSettings.getString(START_PREFERENCES_OBJECT7, String.valueOf(object_7)));
                if (button_object7.getText().equals("")) button_object7.setVisibility(View.INVISIBLE); else button_object7.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT8)) {
                button_object8.setText(mSettings.getString(START_PREFERENCES_OBJECT8, String.valueOf(object_8)));
                if (button_object8.getText().equals("")) button_object8.setVisibility(View.INVISIBLE); else button_object8.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT9)) {
                button_object9.setText(mSettings.getString(START_PREFERENCES_OBJECT9, String.valueOf(object_9)));
                if (button_object9.getText().equals("")) button_object9.setVisibility(View.INVISIBLE); else button_object9.setVisibility(View.VISIBLE);
            }
            if (mSettings.contains(START_PREFERENCES_OBJECT10)) {
                button_object10.setText(mSettings.getString(START_PREFERENCES_OBJECT10, String.valueOf(object_10)));
                if (button_object10.getText().equals("")) button_object10.setVisibility(View.INVISIBLE); else button_object10.setVisibility(View.VISIBLE);
            }

            try {
                ClientThread.StartActivity_Started = true;
                SmsReceiver.StartActivity_Started = true;
            } catch (Exception e) {
                e.printStackTrace();
            }

            String app_pass = "";
            if (mSettings.contains(START_PREFERENCES_APPPASSWORD)) {
                app_pass = mSettings.getString(START_PREFERENCES_APPPASSWORD, "");
            }

            if (need_check_password && app_pass.length() > 0) {
                Intent passwordActivity = new Intent();
                passwordActivity.setClass(mContext, PasswordActivity.class);
                passwordActivity.setAction(PasswordActivity.class.getName());
                //passwordActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                startActivity(passwordActivity);
            } else {
                need_check_password = false;
            }


            if (!start_done && !need_check_password) {
                start_done = true;
                if (mSettings.getBoolean(START_PREFERENCES_RESTORELASTOBJECT, false)) {
                    //restore mainactivity with last used object
                    if (mSettings.contains(START_PREFERENCES_CURRENTOBJECT)) {
                        current_object=Integer.valueOf(mSettings.getString(START_PREFERENCES_CURRENTOBJECT, "0"));
                    }
                    if (current_object>0 && current_object<=objectsSettings.length){
                        Intent intent1 = new Intent(mContext, MainActivity.class);
                        int i=current_object-1;
                        String obj = "";
                        if (i == 0)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT1, String.valueOf(object_1));
                        if (i == 1)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT2, String.valueOf(object_2));
                        if (i == 2)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT3, String.valueOf(object_3));
                        if (i == 3)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT4, String.valueOf(object_4));
                        if (i == 4)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT5, String.valueOf(object_5));
                        if (i == 5)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT6, String.valueOf(object_6));
                        if (i == 6)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT7, String.valueOf(object_7));
                        if (i == 7)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT8, String.valueOf(object_8));
                        if (i == 8)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT9, String.valueOf(object_9));
                        if (i == 9)
                            obj = mSettings.getString(START_PREFERENCES_OBJECT10, String.valueOf(object_10));

                        intent1.putExtra(OBJECT_NAME, obj);
                        intent1.putExtra(OBJECT_SETTING, objectsSettings[i]);
                        startActivityForResult(intent1,current_object);
                    }
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //destroid application

        Log.d(TAG, "StartActivity onDestroy");

        // дерегистрируем (выключаем) BroadcastReceiver
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(br_tcp);
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(br_sms);
        try {
            ClientThread.StartActivity_Started = false;
            SmsReceiver.StartActivity_Started = false;
        }catch (Exception e) {
            e.printStackTrace();
        }
        need_check_password=true;
        start_done = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "StartActivity onStop");
        //hidden application

    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) {
            if (!Settings.canDrawOverlays(this)) {
                // You don't have permission

            }
            else
            {
                //do as per your logic
            }

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.start, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        if (id == R.id.menu_otziv) {
            Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                    "https://play.google.com/store/apps/details?id=" + getPackageName()));
            startActivity(marketIntent);
            return true;
        }

        if (id == R.id.menu_monitor_oko) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(server_url)));
            return true;
        }


        if (id == R.id.menu_about) {
            Intent intent = new Intent(mContext, AboutActivity.class);
            startActivity(intent);
            return true;
        }

        if (id == R.id.menu_settings) {
            Intent intent = new Intent(mContext, SettingsObj.class); //SettingsActivity
            intent.putExtra(OBJECT_SETTING, START_PREFERENCES);
            startActivity(intent);


            return true;
        }

        return super.onOptionsItemSelected(item);

    }



    public void addListenerOnButtonObject1() {

        //--------------------------- обработчик события нажатия кнопки
        button_object1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object1");
                current_object=1;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object1.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[0]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject2() {

        //--------------------------- обработчик события нажатия кнопки
        button_object2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object2");
                current_object=2;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object2.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[1]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);

                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject3() {

        //--------------------------- обработчик события нажатия кнопки
        button_object3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object3");
                current_object=3;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object3.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[2]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject4() {

        //--------------------------- обработчик события нажатия кнопки
        button_object4.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object4");
                current_object=4;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object4.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[3]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject5() {

        //--------------------------- обработчик события нажатия кнопки
        button_object5.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object5");
                current_object=5;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object5.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[4]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject6() {

        //--------------------------- обработчик события нажатия кнопки
        button_object6.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object6");
                current_object=6;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object6.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[5]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject7() {

        //--------------------------- обработчик события нажатия кнопки
        button_object7.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object7");
                current_object=7;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object7.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[6]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject8() {

        //--------------------------- обработчик события нажатия кнопки
        button_object8.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object8");
                current_object=8;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object8.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[7]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject9() {

        //--------------------------- обработчик события нажатия кнопки
        button_object9.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object9");
                current_object=9;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object9.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[8]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }

    public void addListenerOnButtonObject10() {

        //--------------------------- обработчик события нажатия кнопки
        button_object10.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Нажата кнопка Object10");
                current_object=10;
                save_current_object(current_object);
                try {
                    //проигрываем файл
                    //Play_Key_Pressed();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    String message = button_object10.getText().toString();
                    intent.putExtra(OBJECT_NAME, message);
                    intent.putExtra(OBJECT_SETTING, objectsSettings[9]);

                    //startActivity(intent);
                    startActivityForResult(intent,current_object);
                    //return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //-------------------------------------------

    }


    public int hex2decimal(String s) {
        String digits = "0123456789ABCDEF";
        int val = 0;
        try {
            s = s.toUpperCase();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                int d = digits.indexOf(c);
                val = 16 * val + d;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return val;
    }

    private void sms_resend(String message_text, String sender){
        try {
            // --- анализируем входящую смс от
            if (sender != null) {
                try {
                    boolean exist_phone=false;
                    String phone1="", phone2="";
                    SharedPreferences tempSettings;
                    for (int i=0; i< objectsSettings.length; i++){
                        tempSettings= mContext.getSharedPreferences(objectsSettings[i], Context.MODE_PRIVATE);
                        String tt="";
                        if (tempSettings.contains(MainActivity.APP_PREFERENCES_PHONE)) {
                            tt = tempSettings.getString(MainActivity.APP_PREFERENCES_PHONE, "");
                        }

                        phone1=tt;
                        phone2=sender;
                        // ----- сравниеваем номер входной смс с номером прибора - сравниваем "хвост"
                        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;

                        if (exist_phone) {


                            //if (notification_event || (current_object==(i+1))){
                                //check mainactivity state
                                if ( current_object==(i+1)) {
                                    Log.d(TAG, "Resend sms by localbroadcast to current MainActivity, object = " + current_object);
                                    //передаем sms в MainActivity throw local broadcast
                                    try {
                                        Intent intent1 = new Intent(SMS_BROADCAST_TO_MAIN_ACTION);
                                        intent1.putExtra("message", message_text);
                                        intent1.putExtra("sender", sender);
                                        //context.sendBroadcast(intent1);
                                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent1);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                else
                                {
                                    //if (notification_event) {

                                        try {
                                            if (current_object > 0) finishActivity(current_object);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        start_done=true;
                                        MainActivity_Started = false;
                                        current_object = i + 1;
                                        save_current_object(current_object);
                                        Log.d(TAG, "Try relaunch MainActivity for sms, object = " + current_object);
                                        //new Thread(new Runnable() {
                                        //public void run() {
                                        try {
                                            //Intent startActivity = new Intent();
                                            //startActivity.setClass(mContext, MainActivity.class);
                                            //startActivity.setAction(MainActivity.class.getName());
                                            //startActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                                            //startActivity(startActivity);

                                            Intent intent1 = new Intent(mContext, MainActivity.class);

                                            String obj = "";
                                            try {
                                                if (i == 0)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT1, String.valueOf(object_1));
                                                if (i == 1)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT2, String.valueOf(object_2));
                                                if (i == 2)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT3, String.valueOf(object_3));
                                                if (i == 3)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT4, String.valueOf(object_4));
                                                if (i == 4)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT5, String.valueOf(object_5));
                                                if (i == 5)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT6, String.valueOf(object_6));
                                                if (i == 6)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT7, String.valueOf(object_7));
                                                if (i == 7)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT8, String.valueOf(object_8));
                                                if (i == 8)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT9, String.valueOf(object_9));
                                                if (i == 9)
                                                    obj = mSettings.getString(START_PREFERENCES_OBJECT10, String.valueOf(object_10));
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

                                            intent1.putExtra(OBJECT_NAME, obj);
                                            intent1.putExtra(OBJECT_SETTING, objectsSettings[i]);

                                            intent1.putExtra("message", message_text);
                                            intent1.putExtra("sender", sender);
                                            //intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY );
                                            //startActivity(intent1);
                                            startActivityForResult(intent1,current_object);

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        //}
                                        //}).start();
                                    //}

                                }

                            //}

                            break; //i = objectsSettings.length;
                        }
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void save_current_object( int curr_object){
        try {
            SharedPreferences.Editor editor = mSettings.edit();
            editor.putString(START_PREFERENCES_CURRENTOBJECT, String.valueOf(curr_object));
            editor.commit();
            Log.d(TAG, "StartActivity save current object " + curr_object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //********************************* PERMISSION CHECK **************************

    private boolean hasPermission(String permission) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
            return true;
        }
        return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    private void checkPermission(){
        Set<String> missingPermissions = new HashSet<>();
        //if (!hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
        //missingPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        //}
        //if (!hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) {
        //missingPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        //}

        if (!hasPermission(Manifest.permission.SEND_SMS)) {
            missingPermissions.add(Manifest.permission.SEND_SMS);
        }

        if (!hasPermission(Manifest.permission.INTERNET)) {
            missingPermissions.add(Manifest.permission.INTERNET);
        }

        //if (!hasPermission(Manifest.permission.SYSTEM_ALERT_WINDOW)) {
            //missingPermissions.add(Manifest.permission.SYSTEM_ALERT_WINDOW );
        //}

        if (missingPermissions.isEmpty()) {
            //permission = true;
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]),
                        PERMISSIONS_REQUEST_SMS);
            }
            return;
        }

        checkOverlayPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_SMS) {
            //boolean granted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    //granted = false;
                    break;
                }
            }

        }
    }

    private void checkOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
            }
        }
    }
}
