public class MainActivity extends FragmentActivity {
    public static final int PREMISSION_REQUEST_CODE = 1;
    public static final int DRAW_OVER_APPS_REQUEST_CODE = 2;
    public static final String IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP = "com.integreight.onesheeld.IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP";
    public static String currentShieldTag = null;
    public static MainActivity thisInstance;
    public AppSlidingLeftMenu appSlidingMenu;
    public boolean isForground = false;
    private boolean isBackPressed = false;
    TextView oneSheeldLogo;

    private CopyOnWriteArrayList<OnSlidingMenueChangeListner> onChangeSlidingLockListeners = new CopyOnWriteArrayList<>();

    public OneSheeldApplication getThisApplication() {
        return (OneSheeldApplication) getApplication();
    }

    //    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        handleNotificationWithUrlIntent(getIntent());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(Color.parseColor("#CC3a3a3a"));
        }
        setContentView(R.layout.one_sheeld_main);
        oneSheeldLogo = (TextView) findViewById(R.id.currentViewTitle);
        initLooperThread();
        if (savedInstance == null || getThisApplication().isConnectedToBluetooth()) {
//            if (savedInstance != null) {
//                int count = getSupportFragmentManager().getBackStackEntryCount();
//                while (count > 0) {
//                    getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().getFragments().get(count)).commit();
//                    count --;
//                }
//            }
            replaceCurrentFragment(R.id.appTransitionsContainer,
                    SheeldsList.getInstance(), "base", true, false);
        }
        postConfigChange();
        resetSlidingMenu();
        thisInstance = this;
        if (getThisApplication().getShowTutAgain()
                && getThisApplication().getTutShownTimes() < 6)
            startActivity(new Intent(MainActivity.this, Tutorial.class));
        AppRate.with(this)
                .setInstallDays(7)
                .setLaunchTimes(5)
                .setRemindInterval(2)
                .setOnClickButtonListener(new OnClickButtonListener() { // callback listener.
                    @Override
                    public void onClickButton(int which) {
                        Map<String, String> hit = null;
                        switch (which) {
                            case Dialog.BUTTON_NEGATIVE:
                                hit = new HitBuilders.EventBuilder()
                                        .setCategory("App Rating Dialog")
                                        .setAction("No")
                                        .build();
                                break;
                            case Dialog.BUTTON_NEUTRAL:
                                hit = new HitBuilders.EventBuilder()
                                        .setCategory("App Rating Dialog")
                                        .setAction("Later")
                                        .build();
                                break;
                            case Dialog.BUTTON_POSITIVE:
                                hit = new HitBuilders.EventBuilder()
                                        .setCategory("App Rating Dialog")
                                        .setAction("Yes")
                                        .build();
                                break;
                        }
                        if (hit != null) getThisApplication()
                                .getTracker()
                                .send(hit);
                    }
                })
                .monitor();
    }

    public Thread looperThread;
    public Handler backgroundThreadHandler;
    Handler versionHandling = new Handler();
    public OneSheeldVersionQueryCallback versionQueryCallback = new OneSheeldVersionQueryCallback() {
        ValidationPopup popub;

        @Override
        public void onFirmwareVersionQueryResponse(OneSheeldDevice device, FirmwareVersion firmwareVersion) {
            super.onFirmwareVersionQueryResponse(device, firmwareVersion);
            final int minorVersion = firmwareVersion.getMinorVersion();
            final int majorVersion = firmwareVersion.getMajorVersion();
            versionHandling.post(new Runnable() {

                @Override
                public void run() {
                    Log.d("Onesheeld", minorVersion + "     " + majorVersion);
                    if (getThisApplication().getMinorVersion() != -1
                            && getThisApplication().getMajorVersion() != -1) {
                        if (majorVersion == getThisApplication()
                                .getMajorVersion()
                                && minorVersion != getThisApplication()
                                .getMinorVersion()) {
                            String msg = "";
                            try {
                                JSONObject obj = new JSONObject(
                                        ((OneSheeldApplication) getApplication())
                                                .getVersionWebResult());
                                try {
                                    msg += obj.getString("name") + "\n";
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                                try {
                                    msg += obj.getString("description") + "\n";
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                                try {
                                    msg += obj.getString("date");
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            popub = new ValidationPopup(
                                    MainActivity.this,
                                    getString(R.string.firmware_upgrade_decision_dialog_optional_firmware_upgrade),
                                    msg,
                                    new ValidationPopup.ValidationAction(getString(R.string.firmware_upgrade_decision_dialog_now_button),
                                            new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    new FirmwareUpdatingPopup(
                                                            MainActivity.this/*
                                                                             * ,
																			 * false
																			 */)
                                                            .show();
                                                }
                                            }, true),
                                    new ValidationPopup.ValidationAction(
                                            getString(R.string.firmware_upgrade_decision_dialog_not_now_button),
                                            new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    // TODO Auto-generated
                                                    // method
                                                    // stub

                                                }
                                            }, true));
                            if (!isFinishing())
                                popub.show();
                        } else if (majorVersion != getThisApplication()
                                .getMajorVersion()) {
                            String msg = "";
                            try {
                                JSONObject obj = new JSONObject(
                                        ((OneSheeldApplication) getApplication())
                                                .getVersionWebResult());
                                try {
                                    msg += obj.getString("name") + "\n";
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                                try {
                                    msg += obj.getString("description") + "\n";
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                                try {
                                    msg += obj.getString("date");
                                } catch (Exception e) {
                                    // TODO: handle exception
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            popub = new ValidationPopup(MainActivity.this,
                                    getString(R.string.firmware_upgrade_decision_dialog_required_firmware_upgrade), msg,
                                    new ValidationPopup.ValidationAction(
                                            getString(R.string.firmware_upgrade_decision_dialog_start),
                                            new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    FirmwareUpdatingPopup fup = new FirmwareUpdatingPopup(
                                                            MainActivity.this/*
                                                                             * ,
																			 * false
																			 */
                                                    );
                                                    fup.setCancelable(false);
                                                    fup.show();
                                                }
                                            }, true));
                            if (!isFinishing())
                                popub.show();
                        }
                    }
                }
            });
            getThisApplication().getTracker().send(
                    new HitBuilders.ScreenViewBuilder().setCustomDimension(1,
                            majorVersion + "." + minorVersion).build());
        }

        @Override
        public void onLibraryVersionQueryResponse(OneSheeldDevice device, final int libraryVersion) {
            super.onLibraryVersionQueryResponse(device, libraryVersion);
            versionHandling.post(new Runnable() {

                @Override
                public void run() {
                    if (libraryVersion < OneSheeldApplication.ARDUINO_LIBRARY_VERSION) {
                        popub = new ValidationPopup(
                                MainActivity.this,
                                getString(R.string.library_upgrade_dialog_arduino_library_update),
                                getString(R.string.library_upgrade_dialog_theres_a_new_version_of_1sheelds_arduino_library_available_on_our_website),
                                new ValidationPopup.ValidationAction(getString(R.string.library_upgrade_dialog_ok_button),
                                        new View.OnClickListener() {

                                            @Override
                                            public void onClick(View v) {
                                                popub.dismiss();
                                            }
                                        }, true));
                        if (!isFinishing())
                            popub.show();
                    }
                    getThisApplication().getTracker().send(
                            new HitBuilders.ScreenViewBuilder()
                                    .setCustomDimension(2, libraryVersion + "")
                                    .build());
                }
            });
        }
    };
    boolean isConfigChanged = false;
    long pausingTime = 0;
    private onConnectedToBluetooth onConnectToBlueTooth = null;
    private Looper backgroundHandlerLooper;
    private BackOnconnectionLostHandler backOnConnectionLostHandler;

    private void stopLooperThread() {
        if (looperThread != null && looperThread.isAlive()) {
            looperThread.interrupt();
            backgroundHandlerLooper.quit();
            looperThread = null;
        }
    }

    public void initLooperThread() {
        stopLooperThread();
        looperThread = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Looper.prepare();
                backgroundHandlerLooper = Looper.myLooper();
                backgroundThreadHandler = new Handler();
                Looper.loop();
            }
        });
        looperThread.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        thisInstance = this;
    }

    public BackOnconnectionLostHandler getOnConnectionLostHandler() {
        if (backOnConnectionLostHandler == null) {
            backOnConnectionLostHandler = new BackOnconnectionLostHandler(this);
        }
        return backOnConnectionLostHandler;
    }

    @Override
    public void onBackPressed() {
        Log.d("Test", "Back Pressed");
        ///// Camera Preview
        if (getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name()) != null)
            try {
                ((CameraShield) getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name())).hidePreview();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        if (getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name()) != null)
            try {
                ((ColorDetectionShield) getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name())).hidePreview();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        if (getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name()) != null)
            try {
                ((FaceDetectionShield) getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name())).hidePreview();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        resetSlidingMenu();
        MultiDirectionSlidingDrawer pinsView = (MultiDirectionSlidingDrawer) findViewById(R.id.pinsViewSlidingView);
        MultiDirectionSlidingDrawer settingsView = (MultiDirectionSlidingDrawer) findViewById(R.id.settingsSlidingView);
        if ((pinsView == null || (pinsView != null && !pinsView.isOpened()))
                && (settingsView == null || (settingsView != null && !settingsView
                .isOpened()))) {
            if (appSlidingMenu.isOpen()) {
                appSlidingMenu.closePane();
            } else {
                if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
                    findViewById(R.id.getAvailableDevices).setOnClickListener(
                            new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                }
                            });
                    if (findViewById(R.id.isMenuOpening) != null)
                        ((CheckBox) findViewById(R.id.isMenuOpening))
                                .setChecked(false);
                    getSupportFragmentManager().popBackStack();// ("operations",FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    getSupportFragmentManager().executePendingTransactions();
                } else {
                    moveTaskToBack(true);
                }
            }
        } else {
            if (pinsView.isOpened())
                pinsView.animateOpen();
            else if (settingsView.isOpened())
                settingsView.animateOpen();
        }
    }

    private void killAllProcesses() {
        Process.killProcess(Process.myPid());
    }

    public void replaceCurrentFragment(int container, Fragment targetFragment,
                                       String tag, boolean addToBackStack, boolean animate) {
        if (!isFinishing()) {
            FragmentManager manager = getSupportFragmentManager();
            boolean fragmentPopped = manager.popBackStackImmediate(tag, 0);

            if (!fragmentPopped && manager.findFragmentByTag(tag) == null) {
                FragmentTransaction ft = manager.beginTransaction();
                if (animate)
                    ft.setCustomAnimations(R.anim.slide_out_right,
                            R.anim.slide_in_left, R.anim.slide_out_left,
                            R.anim.slide_in_right);
                ft.replace(container, targetFragment, tag);
                if (addToBackStack) {
                    ft.addToBackStack(tag);
                }
                ft.commit();
            }
        }
    }

    public void stopService() {
        this.stopService(new Intent(this, OneSheeldService.class));
    }

    public void finishManually() {
        isBackPressed = true;
        finish();
        destroyIt();
    }

    private void preConfigChange() {
        Enumeration<String> enumKey = ((OneSheeldApplication)
                getApplication()).getRunningShields().keys();
        while (enumKey.hasMoreElements()) {
            String key = enumKey.nextElement();
            ((OneSheeldApplication) getApplication())
                    .getRunningShields().get(key).preConfigChangeThis();
        }
    }

    private void postConfigChange() {
        Enumeration<String> enumKey = ((OneSheeldApplication)
                getApplication()).getRunningShields().keys();
        while (enumKey.hasMoreElements()) {
            String key = enumKey.nextElement();
            ((OneSheeldApplication) getApplication())
                    .getRunningShields().get(key).updateActivty(this);
            ((OneSheeldApplication) getApplication())
                    .getRunningShields().get(key).postConfigChangeThis();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        isConfigChanged = true;
        preConfigChange();
        super.onConfigurationChanged(newConfig);
        postConfigChange();
    }

    private void destroyIt() {
        if (!isConfigChanged) {
            getThisApplication().getTracker().send(
                    new HitBuilders.EventBuilder().setCategory("App lifecycle")
                            .setAction("Finished the app manually").build());
            ArduinoConnectivityPopup.isOpened = false;
            stopService();
            stopLooperThread();
            moveTaskToBack(true);
            OneSheeldSdk.getManager().disconnectAll();
            // // unExpeted
            if (!isBackPressed) {
                Enumeration<String> enumKey = ((OneSheeldApplication)
                        getApplication()).getRunningShields().keys();
                while (enumKey.hasMoreElements()) {
                    String key = enumKey.nextElement();
                    ((OneSheeldApplication) getApplication())
                            .getRunningShields().get(key).resetThis();
                    ((OneSheeldApplication) getApplication())
                            .getRunningShields().remove(key);
                }
                Intent in = new Intent(getIntent());
                PendingIntent intent = PendingIntent.getActivity(
                        getBaseContext(), 0, in, getIntent().getFlags());
                AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mgr.setExact(AlarmManager.RTC, System.currentTimeMillis() + 100,
                            intent);
                } else {
                    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100,
                            intent);
                }
                killAllProcesses();
            } else
                killAllProcesses();
        }
        isConfigChanged = false;
        isBackPressed = false;
    }

    @Override
    protected void onDestroy() {
        ArduinoConnectivityPopup.isOpened = false;
        super.onDestroy();
    }

    public void openMenu() {
        resetSlidingMenu();
        appSlidingMenu.openPane();
    }

    public boolean isMenuOpened() {
        resetSlidingMenu();
        return appSlidingMenu.isOpen();
    }

    public void closeMenu() {
        resetSlidingMenu();
        appSlidingMenu.closePane();
    }

    public void enableMenu() {
        resetSlidingMenu();
        appSlidingMenu.setCanSlide(true);
    }

    public void disableMenu() {
        resetSlidingMenu();
        appSlidingMenu.closePane();
        appSlidingMenu.setCanSlide(false);
    }

    private void resetSlidingMenu() {
        if (appSlidingMenu == null) {
            appSlidingMenu = (AppSlidingLeftMenu) findViewById(R.id.sliding_pane_layout);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                appSlidingMenu.setFitsSystemWindows(true);
            appSlidingMenu.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() {
                @Override
                public void onPanelSlide(View panel, float slideOffset) {

                }

                @Override
                public void onPanelOpened(View panel) {

                }

                @Override
                public void onPanelClosed(View panel) {
                    if (onChangeSlidingLockListeners != null && onChangeSlidingLockListeners.size() > 0) {
                        for (OnSlidingMenueChangeListner onChangeListener : onChangeSlidingLockListeners) {
                            onChangeListener.onMenuClosed();
                        }
                    }
                }
            });
        }
    }

    public void setOnConnectToBluetooth(onConnectedToBluetooth listener) {
        this.onConnectToBlueTooth = listener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SheeldsList.REQUEST_CONNECT_DEVICE:
                break;
            case SheeldsList.REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode != Activity.RESULT_OK) {
                    Toast.makeText(this, R.string.general_toasts_bluetooth_was_not_enabled_toast,
                            Toast.LENGTH_SHORT).show();
                } else {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                        if (onConnectToBlueTooth != null
                                && ArduinoConnectivityPopup.isOpened && !((OneSheeldApplication) getApplication()).getIsDemoMode())
                            onConnectToBlueTooth.onConnect();
                    } else {
                        checkAndAskForLocationPermission();
                    }
                }
                break;
            case DRAW_OVER_APPS_REQUEST_CODE:
                if (canDrawOverApps()) {
                    showToast(getString(R.string.main_activity_draw_over_apps_enabled_you_can_select_the_shield));
                } else {
                    showToast(getString(R.string.main_activity_draw_over_apps_was_not_enabled));
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public Boolean checkForLocationPermission() {
        return (ContextCompat.checkSelfPermission(thisInstance,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED);
    }

    public void checkAndAskForLocationPermission() {
        if (ContextCompat.checkSelfPermission(thisInstance,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisInstance,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                AlertDialog.Builder locationPremissionExplanationDialog = new AlertDialog.Builder(thisInstance);
                locationPremissionExplanationDialog.setMessage(R.string.main_activity_bluetooth_scan_needs_location_permission).setPositiveButton(R.string.main_activity_allow_button, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(thisInstance,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                                MainActivity.PREMISSION_REQUEST_CODE);
                    }
                }).setNegativeButton(R.string.main_activity_deny_button, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showToast(getString(R.string.main_activity_location_permission_denied));
                    }
                }).create();
                locationPremissionExplanationDialog.show();

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(thisInstance,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.LOCATION_HARDWARE},
                        MainActivity.PREMISSION_REQUEST_CODE);
            }
        } else {
            if (onConnectToBlueTooth != null
                    && ArduinoConnectivityPopup.isOpened)
                onConnectToBlueTooth.onConnect();
        }
    }

    @Override
    protected void onResumeFragments() {
        thisInstance = this;
        isForground = true;
        CrashlyticsUtils.setString("isBackground", "No");
        new Thread(new Runnable() {

            @Override
            public void run() {
                ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningAppProcessInfo> appProcesses = activityManager
                        .getRunningAppProcesses();
                if(appProcesses!=null) {
                    String apps = "";
                    for (int i = 0; i < appProcesses.size(); i++) {
                        Log.d("Executed app", "Application executed : "
                                + appProcesses.get(i).processName + "\t\t ID: "
                                + appProcesses.get(i).pid + "");
                        apps += appProcesses.get(i).processName + "\n";
                    }
                    CrashlyticsUtils.setString("Running apps", apps);
                }
            }
        }).start();

        super.onResumeFragments();
        resumeNfcMainActivityFragments();
    }

    private void resumeNfcMainActivityFragments() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
            if (((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {
                PackageManager packageManager = getApplicationContext().getPackageManager();
                packageManager.setComponentEnabledSetting(new ComponentName("com.integreight.onesheeld", "com.integreight.onesheeld.NFCUtils-alias"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
                ((NfcShield) ((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name())).setupForegroundDispatch();
            }
        }
    }

    @Override
    protected void onPause() {
        isForground = false;
        pausingTime = System.currentTimeMillis();
        float hours = TimeUnit.MILLISECONDS.toSeconds(System
                .currentTimeMillis() - pausingTime);
        float minutes = TimeUnit.MILLISECONDS.toMinutes(System
                .currentTimeMillis() - pausingTime);
        float seconds = TimeUnit.MILLISECONDS.toHours(System
                .currentTimeMillis() - pausingTime);
        CrashlyticsUtils.setString("isBackground", "since " + hours + " hours - "
                + minutes + " minutes - " + seconds + " seconds");
        new Thread(new Runnable() {

            @Override
            public void run() {
                ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningAppProcessInfo> appProcesses = activityManager
                        .getRunningAppProcesses();
                String apps = "";
                for (int i = 0; i < appProcesses.size(); i++) {
                    Log.d("Executed app", "Application executed : "
                            + appProcesses.get(i).processName + "\t\t ID: "
                            + appProcesses.get(i).pid + "");
                    apps += appProcesses.get(i).processName + "  ||||||  ";
                }
                CrashlyticsUtils.setString("Running apps", apps);
            }
        }).start();
        pauseMainActivityNfc();
        super.onPause();
    }

    private void pauseMainActivityNfc() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
            if (((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {
                PackageManager packageManager = getApplicationContext().getPackageManager();
                packageManager.setComponentEnabledSetting(new ComponentName("com.integreight.onesheeld", "com.integreight.onesheeld.NFCUtils-alias"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
                ((NfcShield) ((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name())).stopForegroundDispatch();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onNewIntent(final Intent intent) {
        if (intent!=null && intent.getStringExtra("url")!=null && intent.getStringExtra("url").length()>0){
            handleNotificationWithUrlIntent(intent);
        }
        else if (getThisApplication().getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {
            if (findViewById(R.id.progressShieldInit) != null && getSupportFragmentManager().findFragmentByTag(ShieldsOperations.class.getName()) == null) {
                findViewById(R.id.progressShieldInit)
                        .setVisibility(View.VISIBLE);
                findViewById(R.id.operationsLogo)
                        .setVisibility(View.INVISIBLE);
                findViewById(R.id.operationsLogo).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        findViewById(R.id.progressShieldInit)
                                .setVisibility(View.INVISIBLE);
                        findViewById(R.id.operationsLogo)
                                .setVisibility(View.VISIBLE);
                    }
                }, 1000);
            }
        }
        backgroundThreadHandler.post(new Runnable() {
            @Override
            public void run() {
                getNfcIntent(intent);
            }
        });
        super.onNewIntent(intent);
    }

    private void getNfcIntent(Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            if (action != null)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
                    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
                        if (getThisApplication().getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {
                            ((NfcShield) ((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name())).handleIntent(intent);
                        }
                    }
                }
        }
    }

    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void showToast(int msgId) {
        Toast.makeText(this, msgId, Toast.LENGTH_SHORT).show();
    }

    public void hideSoftKeyboard() {
        if (getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
                    .getWindowToken(), 0);
        }
    }

    public void registerSlidingMenuListner(OnSlidingMenueChangeListner listner) {
        if (!onChangeSlidingLockListeners.contains(listner))
            onChangeSlidingLockListeners.add(listner);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PREMISSION_REQUEST_CODE) {
            if (permissions.length > 0) {
                switch (permissions[0]) {
                    case Manifest.permission.ACCESS_FINE_LOCATION:
                        if (grantResults.length > 0
                                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                            if (onConnectToBlueTooth != null
                                    && ArduinoConnectivityPopup.isOpened)
                                onConnectToBlueTooth.onConnect();
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION))
                                    showToast(getString(R.string.main_activity_location_permission_denied));
                                else
                                    showToast(getString(R.string.main_activity_please_turn_on_location_permission));
                            }
                        }
                        break;
                    default:
                        Boolean isEnabled = true;
                        for (int permissionsCount = 0; permissionsCount < grantResults.length; permissionsCount++) {
                            if (grantResults[permissionsCount] != PackageManager.PERMISSION_GRANTED)
                                isEnabled = false;
                        }
                        if (isEnabled) {
                            showToast(getString(R.string.general_toasts_you_can_select_the_shield_now_toast));
                            // permission was granted, yay! Do the
                            // contacts-related task you need to do.
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                Boolean isShouldShowRequestPermissionRationale = true;
                                for (int permissionsCount = 0; permissionsCount < permissions.length; permissionsCount++) {
                                    if (shouldShowRequestPermissionRationale(permissions[permissionsCount]) && grantResults[permissionsCount] != PackageManager.PERMISSION_GRANTED)
                                        isShouldShowRequestPermissionRationale = false;
                                }
                                if (!isShouldShowRequestPermissionRationale)
                                    showToast(getString(R.string.main_activity_this_shield_needs_some_permissions));
                                else
                                    showToast(getString(R.string.main_activity_your_device_didnt_allow_this_shield_permissions));
                            } else {
                                showToast(getString(R.string.main_activity_this_shield_needs_some_permissions));
                            }
                        }
                        break;
                }
            }
            return;
        }
    }

    public void showMenuButtonTutorialOnce() {
        if (Build.VERSION.SDK_INT >= 11 && oneSheeldLogo != null) {
            ViewTarget target = new ViewTarget(oneSheeldLogo);
            if (!getThisApplication().getAppPreferences().getBoolean(IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP, false)) {
                new ShowcaseView.Builder(this)
                        .setTarget(target)
                        .withMaterialShowcase()
                        .setContentTitle(getString(R.string.context_menu_tutorial_open_context_menu))
                        .setContentText(getString(R.string.context_menu_tutorial_upgrade_the_firmware_clear_the_automatic_connection_and_see_the_tutorial_again_after_opening_the_context_menu_by_clicking_on_1sheeld_logo))
                        .setStyle(R.style.CustomShowcaseTheme)
                        .hideOnTouchOutside()
                        .build().hideButton();
                getThisApplication().getAppPreferences().edit().putBoolean(IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP, true).commit();
            }
        }
    }

    public boolean canDrawOverApps() {
        if (Build.VERSION.SDK_INT >= 23) {
            return Settings.canDrawOverlays(this);
        }
        return true;
    }

    public void requestDrawOverApps() {
        if (!canDrawOverApps()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, DRAW_OVER_APPS_REQUEST_CODE);
        }
    }

    public interface OnSlidingMenueChangeListner {
        public void onMenuClosed();
    }

    private void handleNotificationWithUrlIntent(Intent intent) {
        if (intent != null && intent.getStringExtra("url") != null && intent.getStringExtra("url").length() > 0) {
            String url = intent.getStringExtra("url");
            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                url = "http://" + url;
            }
            Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(notificationIntent);
//            finish();
        }
    }

    public class BackOnconnectionLostHandler extends Handler {
        public boolean canInvokeOnCloseConnection = true,
                connectionLost = false;

        private final WeakReference<MainActivity> mTarget;

        public BackOnconnectionLostHandler(MainActivity activity) {
            this.mTarget = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final MainActivity activity = mTarget.get();
            if (activity != null) {
                if (!((OneSheeldApplication) activity.getApplication()).getIsDemoMode() && !getThisApplication().isConnectedToBluetooth()) {
                    if (connectionLost) {
                        if (!ArduinoConnectivityPopup.isOpened
                                && !activity.isFinishing())
                            activity.runOnUiThread(new Runnable() {
                                public void run() {
                                    if (!ArduinoConnectivityPopup.isOpened
                                            && !activity.isFinishing()) {
                                        new ArduinoConnectivityPopup(
                                                activity).show();
                                    }
                                }
                            });
                        if (activity.getSupportFragmentManager()
                                .getBackStackEntryCount() > 1) {
                            activity.getSupportFragmentManager().beginTransaction()
                                    .setCustomAnimations(0, 0, 0, 0)
                                    .commitAllowingStateLoss();
                            activity.getSupportFragmentManager().popBackStack();// ("operations",FragmentManager.POP_BACK_STACK_INCLUSIVE);
                            activity.getSupportFragmentManager()
                                    .executePendingTransactions();
                        }
                    }
                    connectionLost = false;
                }
            }
            super.handleMessage(msg);
        }
    }
} public enum UIShield {
    LED_SHIELD((byte) 0x02, R.string.led_shield_name, 0xff03d203, R.drawable.shields_list_led_symbol, false, LedShield.class, LedFragment.class),
    NOTIFICATION_SHIELD((byte) 0x06, R.string.notifications_shield_name, 0xffd4d903, R.drawable.shields_list_notifications_symbol, false, NotificationShield.class, NotificationFragment.class),
    SEVENSEGMENT_SHIELD((byte) 0x07, R.string.seven_segment_shield_name, 0xffe28203, R.drawable.shields_list_seven_segment_symbol, false, SevenSegmentShield.class, SevenSegmentFragment.class),
    BUZZER_SHIELD((byte) 0x08, R.string.buzzer_shield_name, 0xffe93f03, R.drawable.shields_list_buzzer_symbol, false, SpeakerShield.class, BuzzerFragment.class),
    MIC_SHIELD((byte) 0x18, R.string.mic_shield_name, 0xff0362c0, R.drawable.shields_list_mic_symbol, false, MicShield.class, MicFragment.class, 1),
    KEYPAD_SHIELD((byte) 0x09, R.string.keypad_shield_name, 0xff03c0ae, R.drawable.shields_list_keypad_symbol, false, KeypadShield.class, KeypadFragment.class),
    SLIDER_SHIELD((byte) 0x01, R.string.slider_shield_name, 0xffc0034c, R.drawable.shields_list_slider_symbol, false, SliderShield.class, SliderFragment.class),
    LCD_SHIELD((byte) 0x17, R.string.lcd_shield_name, 0xff99bd03, R.drawable.shields_list_lcd_symbol, false, LcdShield.class, LcdFragment.class, true),
    MAGNETOMETER_SHIELD((byte) 0x0A, R.string.magnetometer_shield_name, 0xff40039f, R.drawable.shields_list_magnetometer_symbol, false, MagnetometerShield.class, MagnetometerFragment.class, 1),
    PUSHBUTTON_SHIELD((byte) 0x03, R.string.push_button_shield_name, 0xffb97547, R.drawable.shields_list_push_button_symbol, false, PushButtonShield.class, PushButtonFragment.class),
    TOGGLEBUTTON_SHIELD((byte) 0x04, R.string.toggle_button_shield_name, 0xffc0039d, R.drawable.shields_list_push_button_symbol, false, ToggleButtonShield.class, ToggleButtonFragment.class),
    ACCELEROMETER_SHIELD((byte) 0x0B, R.string.accelerometer_shield_name, 0xff266a5d, R.drawable.shields_list_accelerometer_symbol, false, AccelerometerShield.class, AccelerometerFragment.class, 1),
    FACEBOOK_SHIELD((byte) 0x19, R.string.facebook_shield_name, 0xff039dc0, R.drawable.shields_list_facebook_symbol, false, FacebookShield.class, FacebookFragment.class, 1),
    TWITTER_SHIELD((byte) 0x1A, R.string.twitter_shield_name, 0xffa14c4c, R.drawable.shields_list_twitter_symbol, false, TwitterShield.class, TwitterFragment.class, 1),
    GAMEDPAD_SHIELD((byte) 0x0C, R.string.game_pad_shield_name, 0xff658f08, R.drawable.shields_list_gamepad_symbol, false, GamepadShield.class, GamepadFragment.class),
    FOURSQUARE_SHIELD((byte) 0x1B, R.string.foursquare_shield_name, 0xff061179, R.drawable.shields_list_foursquare_symbol, false, FoursquareShield.class, FoursquareFragment.class),
    GPS_SHIELD((byte) 0x1C, R.string.gps_shield_name, 0xffa10b07, R.drawable.shields_list_gps_symbol, false, GpsShield.class, GpsFragment.class, 1),
    SMS_SHIELD((byte) 0x0D, R.string.sms_shield_name, 0xffdb7f40, R.drawable.shields_list_sms_symbol, false, SmsShield.class, SmsFragment.class, 1),
    MUSICPLAYER_SHIELD((byte) 0x1D, R.string.music_player_shield_name, 0xffb950e9, R.drawable.shields_list_musicplayer_symbol, false, MusicShield.class, MusicPlayerFragment.class, 1),
    GYROSCOPE_SHIELD((byte) 0x0E, R.string.gyroscope_shield_name, 0xff4c84e9, R.drawable.shields_list_gyroscope_symbol, false, GyroscopeShield.class, GyroscopeFragment.class, 1),
    SKYPE_SHIELD((byte) 0x1F, R.string.skype_shield_name, 0xff08c473, R.drawable.shields_list_skype_symbol, false, SkypeShield.class, SkypeFragment.class),
    PROXIMITY_SHIELD((byte) 0x13, R.string.proximity_shield_name, 0xff543c8d, R.drawable.shields_list_proximity_symbol, false, ProximityShield.class, ProximityFragment.class, 1),
    GRAVITY_SHIELD((byte) 0x14, R.string.gravity_shield_name, 0xffd95342, R.drawable.shields_list_gravity_symbol, false, GravityShield.class, GravityFragment.class, 1),
    ORIENTATION_SHIELD((byte) 0x0F, R.string.orientation_shield_name, 0xff58844f, R.drawable.shields_list_orientation_symbol, false, OrientationShield.class, OrientationFragment.class, 1),
    LIGHT_SHIELD((byte) 0x10, R.string.light_shield_name, 0xff8b268d, R.drawable.shields_list_light_sensor_symbol, false, LightShield.class, LightFragment.class, 1),
    PRESSURE_SHIELD((byte) 0x11, R.string.pressure_shield_name, 0xff67584d, R.drawable.shields_list_pressure_symbol, false, PressureShield.class, PressureFragment.class, 1),
    TEMPERATURE_SHIELD((byte) 0x12, R.string.temperature_shield_name, 0xff999f45, R.drawable.shields_list_temperature_symbol, false, TemperatureShield.class, TemperatureFragment.class, 1),
    CAMERA_SHIELD((byte) 0x15, R.string.camera_shield_name, 0xff6d0347, R.drawable.shields_list_camera_symbol, false, CameraShield.class, CameraFragment.class, 1),
    PHONE_SHIELD((byte) 0x20, R.string.phone_shield_name, 0xffe9bd03, R.drawable.shields_list_phone_symbol, false, PhoneShield.class, PhoneFragment.class, 1),
    EMAIL_SHIELD((byte) 0x1E, R.string.email_shield_name, 0xff114540, R.drawable.shields_list_email_symbol, false, EmailShield.class, EmailFragment.class, 1),
    CLOCK_SHIELD((byte) 0x21, R.string.clock_shield_name, 0xffc45527, R.drawable.shields_list_clock_symbol, false, ClockShield.class, ClockFragment.class),
    KEYBOARD_SHIELD((byte) 0x22, R.string.keyboard_shield_name, 0xffde1f26, R.drawable.shields_list_keyboard_symbol, false, KeyboardShield.class, KeyboardFragment.class),
    TEXT_TO_SPEECH_SHIELD((byte) 0x23, R.string.text_to_speech_shield_name, 0xffde1f26, R.drawable.shields_list_tts_symbol, false, TextToSpeechShield.class, TextToSpeechFragment.class),
    SPEECH_RECOGNIZER_SHIELD((byte) 0x24, R.string.voice_recognizer_shield_name, 0xffde1f26, R.drawable.shields_list_voice_recognition_symbol, false, SpeechRecognitionShield.class, SpeechRecognitionFragment.class, 1),
    DATA_LOGGER((byte) 0x25, R.string.data_logger_shield_name, 0xffde1f26, R.drawable.shields_list_data_logger_symbol, false, DataLoggerShield.class, DataLoggerFragment.class, 1),
    TERMINAL_SHIELD((byte) 0x26, R.string.terminal_shield_name, 0xffde1f26, R.drawable.shields_list_terminal_symbol, false, TerminalShield.class, TerminalFragment.class),
    TASKER_SHIELD((byte) 0x0, R.string.tasker_shield_name, 0xff0b4c8d, R.drawable.shields_list_flashlight_symbol, false, TaskerShield.class, EmptyShieldFragment.class, false),
    PATTERN_SHIELD((byte) 0x27, R.string.pattern_shield_name, 0xffde1f26, R.drawable.shields_list_pattern_symbol, false, PatternShield.class, PatternFragment.class),
    INTERNET_SHIELD((byte) 0x29, R.string.internet_shield_name, 0xffde1f26, R.drawable.shields_list_internet_symbol, false, InternetShield.class, InternetFragment.class, 1),
    NFC_SHIELD((byte) 0x16, R.string.nfc_shield_name, 0xff03d203, R.drawable.shields_list_nfc_symbol, false, NfcShield.class, NfcFragment.class, 1),
    GLCD_SHIELD((byte) 0x28, R.string.glcd_shield_name, 0xff03d203, R.drawable.shields_list_glcd_symbol, false, GlcdShield.class, GlcdFragment.class),
    COLOR_DETECTION_SHIELD((byte) 0x05, R.string.color_detector_shield_name, 0xffde1f26, R.drawable.shields_list_color_detector_symbol, false, ColorDetectionShield.class, ColorDetectionFragment.class, 1),
    VIBRATION_SHIELD((byte) 0x2A, R.string.vibration_shield_name, 0xffde1f26, R.drawable.shields_list_vibration_symbol, false, VibrationShield.class, VibrationFragment.class, 1),
    FACE_DETECTION((byte) 0x2D, R.string.face_detection_shield_name, 0xff0b4c8d, R.drawable.shields_list_face_detection_symbol, false, FaceDetectionShield.class, FaceDetectionFragment.class, 1);
    public static int[] colors = new int[]{0xff03d203, 0xffd4d903,
            0xffe28203, 0xffe93f03, 0xff0362c0, 0xff03c0ae, 0xffc0034c,
            0xff99bd03, 0xff40039f, 0xffb97547, 0xffc0039d, 0xff266a5d,
            0xff039dc0, 0xffa14c4c, 0xff658f08, 0xff061179, 0xffa10b07,
            0xffdb7f40, 0xffb950e9, 0xff4c84e9, 0xff0b4c8d, 0xff08c473,
            0xff543c8d, 0xffd95342, 0xff58844f, 0xff8b268d, 0xff67584d,
            0xff999f45, 0xff6d0347, 0xffe9bd03, 0xff127303, 0xff08bbb2,
            0xff5a0303, 0xff988564, 0xff114540, 0xffc45527, 0xffde1f26,
            0xff142218, 0xffc9a302, 0xffa57378, 0xff3354af, 0xff282742,
            0xff381616, 0xff0b4c8d};
    public static UIShield shieldsActivitySelection;
    public static boolean isConnected = false;
    private byte id;
    private int shieldNameStringResource;
    private int itemBackgroundColor;
    private int symbolId;
    private boolean mainActivitySelection;
    private boolean isReleasable = true;
    private int isInvalidatable = 0;
    private Class<? extends ControllerParent<?>> shieldType;
    private Class<? extends ShieldFragmentParent<?>> shieldFragment;
    private int position = 0;

    UIShield(byte id, int shieldNameStringResource, int mainImageStripId, int symbolId,
             boolean mainActivitySelection,
             Class<? extends ControllerParent<?>> shieldType, Class<? extends ShieldFragmentParent<?>> shieldFragment) {
        this.id = id;
        this.shieldNameStringResource = shieldNameStringResource;
        this.itemBackgroundColor = mainImageStripId;
        this.symbolId = symbolId;
        this.mainActivitySelection = mainActivitySelection;
        this.shieldType = shieldType;
        this.shieldFragment = shieldFragment;
    }

    UIShield(byte id, int shieldNameStringResource, int mainImageStripId, int symbolId,
             boolean mainActivitySelection,
             Class<? extends ControllerParent<?>> shieldType, Class<? extends ShieldFragmentParent<?>> shieldFragment, int isInvalidatable) {
        this.id = id;
        this.shieldNameStringResource = shieldNameStringResource;
        this.itemBackgroundColor = mainImageStripId;
        this.symbolId = symbolId;
        this.mainActivitySelection = mainActivitySelection;
        this.shieldType = shieldType;
        this.shieldFragment = shieldFragment;
        this.isInvalidatable = isInvalidatable;
    }

    UIShield(byte id, int shieldNameStringResource, int mainImageStripId, int symbolId,
             boolean mainActivitySelection,
             Class<? extends ControllerParent<?>> shieldType, Class<? extends ShieldFragmentParent<?>> shieldFragment,
             boolean isReleasable) {
        this.id = id;
        this.shieldNameStringResource = shieldNameStringResource;
        this.itemBackgroundColor = mainImageStripId;
        this.symbolId = symbolId;
        this.mainActivitySelection = mainActivitySelection;
        this.shieldType = shieldType;
        this.shieldFragment = shieldFragment;
        this.isReleasable = isReleasable;
    }

    public static UIShield getShieldsActivitySelection() {
        return shieldsActivitySelection;
    }

    public static void setConnected(boolean isConnected) {
        UIShield.isConnected = isConnected;
    }

    public static synchronized List<UIShield> valuesFiltered() {
        UIShield[] vals = values();
        List<UIShield> valsFiltered = new ArrayList<UIShield>();
        for (int i = 0; i < vals.length; i++) {
            UIShield cur = vals[i];
            if (cur.isReleasable) {
                cur.position = valsFiltered.size();
                valsFiltered.add(cur);
            }
        }
        Collections.sort(valsFiltered, new Comparator<UIShield>() {

            @Override
            public int compare(UIShield lhs, UIShield rhs) {
                return lhs.getName().compareToIgnoreCase(rhs.getName());
            }
        });
        vals = null;
        final ArrayList<UIShield> ret = new ArrayList<UIShield>();
        for (UIShield uiShield : valsFiltered) {
            uiShield.itemBackgroundColor = colors[ret.size()];
            ret.add(uiShield);
        }
        valsFiltered.clear();
        valsFiltered = null;
        return ret;
    }

    public String getName() {
        return OneSheeldApplication.getContext().getString(shieldNameStringResource);
    }

    public byte getId() {
        return id;
    }

    public int getItemBackgroundColor() {
        return itemBackgroundColor;
    }

    public int getSymbolId() {
        return symbolId;
    }

    public boolean isMainActivitySelection() {
        return mainActivitySelection;
    }

    public int getIsInvalidatable() {
        return isInvalidatable;
    }

    public int getPosition() {
        return position;
    }

    public Class<? extends ControllerParent<?>> getShieldType() {
        return shieldType;
    }

    public Class<? extends ShieldFragmentParent<?>> getShieldFragment() {
        return shieldFragment;
    }

    public boolean isReleasable() {
        return isReleasable;
    }
} @SuppressWarnings("unchecked")
public abstract class ShieldFragmentParent<T extends ShieldFragmentParent<?>>
        extends Fragment {
    private String controllerTag = "";// unique key for the shield
    public boolean hasSettings = false;// a flag to check if the shield has
    // Settings sliding drawer or not like
    // music player shield
    public Handler uiHandler = new Handler(); // handler to do UI changes
    public String shieldName = ""; // to be setten on the top of the Shield
    // screen
    public MainActivity activity; // MainActivity Instance to be used in all
    // shields

    public ShieldFragmentParent() {
        controllerTag = AppShields.getInstance().getShieldTag(((T) (this)).getClass().getName());
    }

    @Override
    public void onAttach(Activity activity) {
        this.activity = (MainActivity) activity;
        super.onAttach(activity);
        ((T) this).doOnAttach();
    }

    @Override
    public void onDetach() {
        // activity = null;
        ((T) this).doOnDetach();
        super.onDetach();
    }

    public MainActivity getAppActivity() {
        return (MainActivity) getActivity();
    }

    public OneSheeldApplication getApplication() {
        return activity.getThisApplication();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        activity = getAppActivity();
        controllerTag = AppShields.getInstance().getShieldTag(((T) (this)).getClass().getName());
        super.onActivityCreated(savedInstanceState);
        ((T) this).doOnActivityCreated(savedInstanceState);
    }

    public boolean reInitController() {
        ControllerParent<?> type = null;
        Shield shield = AppShields.getInstance().getShield(getControllerTag());
        if (shield != null) {
            try {
                type = shield.shieldType.newInstance();
            } catch (java.lang.InstantiationException e) {
                // TODO Auto-generated catch block
                Log.e("TAG", "Exception", e);
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                Log.e("TAG", "Exception", e);
            }
            if (type != null) {
                type.setActivity(getAppActivity()).init(shield.tag);
                getApplication().getRunningShields().get(getControllerTag())
                        .setHasForgroundView(true);
                return true;
            }
        } else {
            getActivity().getSupportFragmentManager().beginTransaction()
                    .remove(this).commit();
            onDestroy();
            return false;
        }
        return false;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        if (getApplication().getAppFirmata().isOpen() == false && !getApplication().getIsDemoMode()) return;
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            if (!reInitController())
                return;
        }
        ((T) this).doOnViewCreated(view, savedInstanceState);
    }

    @Override
    public void onStart() {
        Log.d("S", "start");
        super.onStart();
        activity = getAppActivity();
        uiHandler = new Handler();
        /*
         * If the Shield lost it's controller instance within the application,
		 * then starts to re-init it
		 */

            if (getApplication().getRunningShields().get(getControllerTag()) != null && activity != null && activity.findViewById(R.id.settingsFixedHandler) != null)
                getApplication().getRunningShields().get(getControllerTag())
                        .setHasForgroundView(true);
            else {
//            if (!reInitController())
                return;
            }
        // View or hide Setting sliding drawer handler button
        activity.findViewById(R.id.settingsFixedHandler).setVisibility(
                hasSettings ? View.VISIBLE : View.GONE);
        // View or hide Pins sliding drawer handler button
        activity.findViewById(R.id.pinsFixedHandler)
                .setVisibility(
                        getApplication().getRunningShields().get(
                                getControllerTag()) == null
                                || getApplication().getRunningShields().get(
                                getControllerTag()).requiredPinsIndex == -1 ? View.GONE
                                : View.VISIBLE);
        ((T) this).doOnStart();
    }

    @Override
    public void onStop() {
        // stop shield controller form affecting the UI
        ((T) this).doOnStop();
        if (getApplication().getRunningShields().get(getControllerTag()) != null)
            getApplication().getRunningShields().get(getControllerTag())
                    .setHasForgroundView(false);
        uiHandler.removeCallbacksAndMessages(null);
        super.onStop();
    }

    public void doOnServiceConnected() {

    }

    /**
     * @return the Shield notNull controller tag
     * @desc we have 4 backups of the shield tag: (Local variable here,
     * hashtable saved on the application subclass depends on shield
     * fragment name, Shield fragment tag and a fragment tag), So we
     * iterate and ignore null backups and reset them all
     */
    public String getControllerTag() {
        if (controllerTag == null || controllerTag.trim().length() == 0) {
            String tagFromApp = AppShields.getInstance().getShieldTag(((T) (this)).getClass().getName());
            controllerTag = (tagFromApp != null ? tagFromApp
                    : controllerTag != null ? controllerTag
                    : (getArguments() != null && getArguments().getString(
                    "tag") != null) ? getArguments().getString(
                    "tag") : getTag());
            if (controllerTag == null)
                CrashlyticsUtils
                        .log("ControllerTag = null" + ((T) (this)) != null ? ((T) (this))
                                .getClass().getName() : "");
            Log.test("TAG", controllerTag + "  Tag from app:  " + tagFromApp
                    + "  Frag Tag:  " + getTag() + "  Arg:  "
                    + getArguments().getString("tag"));
        }
        getArguments().putString("tag", controllerTag);
        return controllerTag;
    }

    public void setControllerTag(String controllerTag) {
        this.controllerTag = controllerTag;
    }

    @Override
    public void onLowMemory() {
        // TODO Auto-generated method stub
        super.onLowMemory();
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (getApplication().getAppFirmata().isOpen() == false && !getApplication().getIsDemoMode()) return;
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            if (!reInitController())
                return;
        }
        if (activity == null || activity.findViewById(R.id.shieldStatus) == null)
            return;
        MainActivity.currentShieldTag = getControllerTag();
        // restore the staus of shield interaction toggle button
        if (getApplication().getRunningShields().get(getControllerTag()) != null)
            ((ToggleButton) activity.findViewById(R.id.shieldStatus))
                    .setChecked(getApplication().getRunningShields().get(
                            getControllerTag()).isInteractive);
        // Google analytics tracking
        getApplication().getTracker().setScreenName(getControllerTag());
        getApplication().getTracker().send(
                new HitBuilders.ScreenViewBuilder().build());
        // Logging current view for crashlytics
        CrashlyticsUtils.setString("Current View", getTag());
        ((T) this).doOnResume();
    }

    /**
     * @return a flag to check if the fragment read to hold UI changes
     */
    public boolean canChangeUI() {
        if (uiHandler == null)
            uiHandler = new Handler();
        return (getActivity() != null
                && getControllerTag() != null
                && getApplication().getRunningShields().get(getControllerTag()) != null && getApplication()
                .getRunningShields().get(getControllerTag())
                .isHasForgroundView() && getView() != null);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        activity = getAppActivity();
    }

    @Override
    public void onDestroy() {
        ((T) this).doOnDestroy();
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        ((T) this).doOnPause();
    }
    public void doOnStart() {
    }

    public void doOnDestroy() {
    }

    public void doOnResume() {
    }

    public void doOnStop() {
    }

    public void doOnAttach() {
    }

    public void doOnDetach() {
    }

    public void doOnActivityCreated(Bundle savedInstanceStat) {
    }

    public void doOnViewCreated(View view, Bundle savedInstanceStat) {
    }
    public void doOnPause() {}
} public class AccelerometerFragment extends
        ShieldFragmentParent<AccelerometerFragment> {
    TextView x, y, z;
    CheckBox enableLlinearAccelerometer;
    public static boolean isLinearActive = false;
    private static LinearLisenter linearLisenter;

    public static void setLinearLisenter(LinearLisenter Lisenter) {
        linearLisenter = Lisenter;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.accelerometer_shield_fragment_layout,
                container, false);
    }

    @Override
    public void doOnStart() {
        ((AccelerometerShield) getApplication().getRunningShields().get(
                getControllerTag()))
                .setAccelerometerEventHandler(accelerometerEventHandler);
        ((AccelerometerShield) getApplication().getRunningShields().get(
                getControllerTag())).invalidateAccelerometer(true);
    }

    @Override
    public void doOnViewCreated(View v, @Nullable Bundle savedInstanceState) {
        x = (TextView) v.findViewById(R.id.x_value_txt);
        y = (TextView) v.findViewById(R.id.y_value_txt);
        z = (TextView) v.findViewById(R.id.z_value_txt);
        enableLlinearAccelerometer = (CheckBox) v.findViewById(R.id.linear_accelerometer);
        enableLlinearAccelerometer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isLinearActive = isChecked;
                linearLisenter.isLinearActive(isChecked);
                if (!((AccelerometerShield) getApplication().getRunningShields()
                        .get(getControllerTag())).isLinearExist)
                    enableLlinearAccelerometer.setChecked(false);
            }
        });
    }

    @Override
    public void doOnActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

    }

    private AccelerometerEventHandler accelerometerEventHandler = new AccelerometerEventHandler() {

        @Override
        public void onSensorValueChangedFloat(final float[] value) {

            // TODO Auto-generated method stub
            // set data to UI
            x.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI())
                        x.setText("" + value[0]);
                }
            });
            y.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI())
                        y.setText("" + value[1]);
                }
            });
            z.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI())
                        z.setText("" + value[2]);

                }
            });

        }

        @Override
        public void isDeviceHasSensor(final Boolean hasSensor) {
        }
    };

    private void initializeFirmata() {
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            getApplication().getRunningShields().put(getControllerTag(),
                    new AccelerometerShield(activity, getControllerTag()));
        }
    }

    public void doOnServiceConnected() {
        initializeFirmata();
    }

    @Override
    public void doOnResume() {
        enableLlinearAccelerometer.setChecked(isLinearActive);
        linearLisenter.isLinearActive(isLinearActive);
    }

    public static interface LinearLisenter {
        void isLinearActive(Boolean isLinearActive);
    }
} public class CameraFragment extends ShieldFragmentParent<CameraFragment> implements ShieldsOperations.OnChangeListener, MainActivity.OnSlidingMenueChangeListner {
    Bitmap lastImageBitmap;
    private CheckBox frontBackToggle;
    private CheckBox cameraPreviewToggle;
    private ImageView lastImage;
    private View cameraLogo;
    private String lastImageSrc = null;
    private CameraEventHandler cameraEventHandler = new CameraEventHandler() {

        @Override
        public void checkCameraHardware(boolean isHasCamera) {
        }

        @Override
        public void OnPictureTaken() {
        }

        @Override
        public void takePicture() {
        }

        @Override
        public void setFlashMode(String flash_mode) {

        }

        @Override
        public void setOnCameraPreviewTypeChanged(final boolean isBack) {
            if (canChangeUI() && frontBackToggle != null && getView() != null)
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        removeListners();
                        frontBackToggle.setChecked(isBack);
                        applyListeners();
                    }
                });
        }

        @Override
        public void updatePreviewButton(final String lastImagePath) {
            if (canChangeUI() && frontBackToggle != null && getView() != null)
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (lastImagePath != null && !lastImagePath.equals("")) {
                            lastImageSrc = lastImagePath;
                            lastImageBitmap = BitmapFactory.decodeFile(lastImageSrc);
                            if (lastImage != null && lastImageBitmap != null) {
                                lastImageBitmap = Bitmap.createScaledBitmap(lastImageBitmap, 50, 50, true);
                                lastImage.setImageBitmap(lastImageBitmap);
                                lastImage.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (getAppActivity().getSupportFragmentManager().findFragmentByTag(ShieldsOperations.class.getName()) != null)
            ((ShieldsOperations) getAppActivity().getSupportFragmentManager().findFragmentByTag(ShieldsOperations.class.getName())).addOnSlidingLocksListener(this);
        activity.registerSlidingMenuListner(this);
        return inflater.inflate(R.layout.camera_shield_fragment_layout, container,
                false);
    }

    @Override
    public void doOnViewCreated(View view, Bundle savedInstanceState) {
        frontBackToggle = (CheckBox) view.findViewById(R.id.frontBackToggle);
        cameraPreviewToggle = (CheckBox) view.findViewById(R.id.camera_preview_toggle);
        lastImage = (ImageView) view.findViewById(R.id.camera_last_image);
        cameraLogo = view.findViewById(R.id.camera_log);

        activity.backgroundThreadHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    lastImageSrc = CameraUtils.getLastCapturedImagePathFromOneSheeldFolder(activity, false);
                } catch (SecurityException e) {
                }
                if (lastImageSrc != null) {
                    lastImageBitmap = BitmapFactory.decodeFile(lastImageSrc);
                    if (lastImage != null && lastImageBitmap != null) {
                        lastImageBitmap = Bitmap.createScaledBitmap(lastImageBitmap, 50, 50, true);
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                lastImage.setImageBitmap(lastImageBitmap);
                                lastImage.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                } else
                    uiHandler.post(new Runnable() {
                                       @Override
                                       public void run() {
                                           lastImage.setVisibility(View.INVISIBLE);
                                       }
                                   });
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        activity.backgroundThreadHandler.post(new Runnable() {
            @Override
            public void run() {
                if (lastImage != null) {
                    uiHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                lastImage.setAlpha((float) 1);
                            }
                        }
                    });
                    try {
                        lastImageSrc = CameraUtils.getLastCapturedImagePathFromOneSheeldFolder(activity, false);
                    } catch (SecurityException e) {
                    }
                    if (lastImageSrc != null) {
                        lastImageBitmap = BitmapFactory.decodeFile(lastImageSrc);
                        if (lastImage != null && lastImageBitmap != null) {
                            lastImageBitmap = Bitmap.createScaledBitmap(lastImageBitmap, 50, 50, true);
                            uiHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    lastImage.setImageBitmap(lastImageBitmap);
                                    lastImage.setVisibility(View.VISIBLE);
                                }
                            });
                        }
                    } else
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                lastImage.setVisibility(View.INVISIBLE);
                            }
                        });
                }
            }
        });
    }

    @Override
    public void doOnStart() {
        ((CameraShield) getApplication().getRunningShields().get(
                getControllerTag())).setCameraEventHandler(cameraEventHandler);
    }

    private void removeListners() {
        frontBackToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });
        cameraPreviewToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            }
        });
        lastImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private void applyListeners() {
        frontBackToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                boolean feeback = ((CameraShield) getApplication().getRunningShields().get(
                        getControllerTag())).setCameraToPreview(b);
                if (!feeback) {
                    removeListners();
                    frontBackToggle.setChecked(!b);
                    applyListeners();
                }
            }
        });
        cameraPreviewToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    if (!((CheckBox) activity.findViewById(R.id.isMenuOpening)).isChecked())
                        ((CheckBox) activity.findViewById(R.id.isMenuOpening)).setChecked(true);
                    else {
                        if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                            try {
                                if (((CameraShield) getApplication().getRunningShields().get(getControllerTag())).showPreview())
                                    cameraLogo.setVisibility(View.INVISIBLE);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                                removeListners();
                                cameraPreviewToggle.setChecked(false);
                                applyListeners();
                            }
                    }
                } else {
                    if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                        try {
                            if ((((CameraShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview()))
                                cameraLogo.setVisibility(View.VISIBLE);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            removeListners();
                            cameraPreviewToggle.setChecked(true);
                            applyListeners();
                        }
                }
            }
        });
        lastImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                if (lastImageSrc != null) {
                    File img = new File(lastImageSrc);
                    if (img.exists()) {
                        cameraPreviewToggle.setEnabled(false);
                        if (Build.VERSION.SDK_INT >= 24) {
                            Uri fileURI = FileProvider.getUriForFile(activity,
                                    BuildConfig.APPLICATION_ID + ".provider",
                                    img);
                            intent.setDataAndType(fileURI, "image/*");
                        } else {
                            intent.setDataAndType(Uri.fromFile(img), "image/*");
                        }
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        activity.startActivity(intent);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            v.setAlpha((float) 0.5);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void doOnActivityCreated(Bundle savedInstanceState) {
    }

    private void initializeFirmata() {
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            getApplication().getRunningShields().put(getControllerTag(),
                    new CameraShield(activity, getControllerTag()));
        }
    }

    public void doOnServiceConnected() {
        initializeFirmata();
    }

    @Override
    public void doOnResume() {
        uiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                cameraPreviewToggle.setEnabled(true);
                if (activity != null && activity.findViewById(R.id.isMenuOpening) != null) {
                    if (((CheckBox) activity.findViewById(R.id.isMenuOpening)).isChecked() && !activity.isMenuOpened() && cameraPreviewToggle.isChecked()) {
                        try {
                            if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                                if (((CameraShield) getApplication().getRunningShields().get(getControllerTag())).showPreview())
                                    cameraLogo.setVisibility(View.INVISIBLE);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            removeListners();
                            cameraPreviewToggle.setChecked(false);
                            applyListeners();
                        }
                    } else {
                        if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                            try {
                                if (((CameraShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview())
                                    cameraLogo.setVisibility(View.VISIBLE);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                                removeListners();
                                cameraPreviewToggle.setChecked(true);
                                applyListeners();
                            }
                    }
                }
            }
        }, 500);

        try {
            ((CameraShield) getApplication().getRunningShields().get(
                    getControllerTag())).setCameraToPreview(((CameraShield) getApplication().getRunningShields().get(
                    getControllerTag())).isBackPreview());
            ((CameraShield) getApplication().getRunningShields().get(
                    getControllerTag())).invalidatePreview();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        removeListners();
        frontBackToggle.setChecked(((CameraShield) getApplication().getRunningShields().get(
                getControllerTag())).isBackPreview());
        applyListeners();

    }

    @Override
    public void doOnPause() {
        if (getApplication().getRunningShields().get(
                getControllerTag()) != null) {
            try {
                ((CameraShield) getApplication().getRunningShields().get(
                        getControllerTag())).hidePreview();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        cameraLogo.setVisibility(View.VISIBLE);
        if (getView() != null) getView().invalidate();
    }

    @Override
    public void onChange(boolean isChecked) {
        if (canChangeUI() && getView() != null && getApplication().getRunningShields().get(
                getControllerTag()) != null) {
            if (activity != null && activity.findViewById(R.id.isMenuOpening) != null) {
                if (isChecked && !activity.isMenuOpened() && cameraPreviewToggle.isChecked()) {
                    try {
                        if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                            if (((CameraShield) getApplication().getRunningShields().get(getControllerTag())).showPreview())
                                cameraLogo.setVisibility(View.INVISIBLE);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        removeListners();
                        cameraPreviewToggle.setChecked(false);
                        applyListeners();
                    }
                } else if (!isChecked || activity.isMenuOpened()) {
                    try {
                        if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                            if (((CameraShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview())
                                cameraLogo.setVisibility(View.VISIBLE);
                        if (!isChecked && !activity.isMenuOpened()) {
                            removeListners();
                            cameraPreviewToggle.setChecked(false);
                            applyListeners();
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        removeListners();
                        cameraPreviewToggle.setChecked(true);
                        applyListeners();
                    }
                }
            }
        }
    }

    @Override
    public void onMenuClosed() {
        if (canChangeUI() && getView() != null && getApplication().getRunningShields().get(
                getControllerTag()) != null) {
            if (activity != null && activity.findViewById(R.id.isMenuOpening) != null) {
                if (((CheckBox) activity.findViewById(R.id.isMenuOpening)).isChecked() && cameraPreviewToggle.isChecked()) {
                    try {
                        if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                            if (((CameraShield) getApplication().getRunningShields().get(getControllerTag())).showPreview())
                                cameraLogo.setVisibility(View.INVISIBLE);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        removeListners();
                        cameraPreviewToggle.setChecked(false);
                        applyListeners();
                    }
                } else {
                    if ((CameraShield) getApplication().getRunningShields().get(getControllerTag()) != null)
                        try {
                            if (((CameraShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview())
                                cameraLogo.setVisibility(View.VISIBLE);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            removeListners();
                            cameraPreviewToggle.setChecked(true);
                            applyListeners();
                        }
                }
            }
        }
    }
} public class FaceDetectionFragment extends ShieldFragmentParent<FaceDetectionFragment> implements ShieldsOperations.OnChangeListener, MainActivity.OnSlidingMenueChangeListner {

    private CheckBox frontBackToggle;
    private CheckBox cameraPreviewToggle;
    private View facelogo;
    private FaceDetectionHandler faceDetectionHandler = new FaceDetectionHandler() {
        @Override
        public void setOnCameraPreviewTypeChanged(final boolean isBack) {
            if (canChangeUI() && frontBackToggle != null && getView() != null)
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        removeListeners();
                        frontBackToggle.setChecked(isBack);
                        applyListeners();
                    }
                });
        }
    };

    private void removeListeners() {
        frontBackToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });
        cameraPreviewToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            }
        });
    }

    private void applyListeners() {
        frontBackToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                boolean feeback = ((FaceDetectionShield) getApplication().getRunningShields().get(
                        getControllerTag())).setCameraToPreview(b);
                if (!feeback) {
                    removeListeners();
                    frontBackToggle.setChecked(!b);
                    applyListeners();
                }
            }
        });

        cameraPreviewToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    if (!((CheckBox) activity.findViewById(R.id.isMenuOpening)).isChecked())
                        ((CheckBox) activity.findViewById(R.id.isMenuOpening)).setChecked(true);
                    else {
                        if (getApplication().getRunningShields().get(getControllerTag()) != null)
                            try {
                                if (((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).showPreview()) {
                                    facelogo.setVisibility(View.INVISIBLE);
                                    ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(true);
                                }
                            } catch (RemoteException e) {
                                e.printStackTrace();
                                removeListeners();
                                cameraPreviewToggle.setChecked(false);
                                applyListeners();
                            }
                    }
                } else {
                    if (getApplication().getRunningShields().get(getControllerTag()) != null)
                        try {
                            if ((((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview())) {
                                facelogo.setVisibility(View.VISIBLE);
                                ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(false);
                            }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            removeListeners();
                            cameraPreviewToggle.setChecked(true);
                            applyListeners();
                        }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.face_detection_shield_fragment_layout,container,false);
        frontBackToggle = (CheckBox) rootView.findViewById(R.id.frontBackToggle);
        cameraPreviewToggle = (CheckBox) rootView.findViewById(R.id.camera_preview_toggle);
        facelogo = rootView.findViewById(R.id.face_log);
        // Inflate the layout for this fragment
        if (getAppActivity().getSupportFragmentManager().findFragmentByTag(ShieldsOperations.class.getName()) != null)
            ((ShieldsOperations) getAppActivity().getSupportFragmentManager().findFragmentByTag(ShieldsOperations.class.getName())).addOnSlidingLocksListener(this);
        activity.registerSlidingMenuListner(this);
        return rootView;
    }

    @Override
    public void doOnViewCreated(View view, Bundle savedInstanceState) {


    }

    @Override
    public void doOnStart() {
        ((FaceDetectionShield) getApplication().getRunningShields().get(
                getControllerTag())).setCameraEventHandler(faceDetectionHandler);
    }

    private void initializeFirmata() {
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            getApplication().getRunningShields().put(getControllerTag(),
                    new FaceDetectionShield(activity, getControllerTag()));
        }
    }

    public void doOnServiceConnected() {
        initializeFirmata();
    }

    @Override
    public void doOnResume() {
        uiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                cameraPreviewToggle.setEnabled(true);
                if (activity != null && activity.findViewById(R.id.isMenuOpening) != null) {
                    if (((CheckBox) activity.findViewById(R.id.isMenuOpening)).isChecked() && !activity.isMenuOpened() && cameraPreviewToggle.isChecked()) {
                        try {
                            if (getApplication().getRunningShields().get(getControllerTag()) != null)
                                if (((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).showPreview()) {
                                    facelogo.setVisibility(View.INVISIBLE);
                                    ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(true);
                                }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            removeListeners();
                            cameraPreviewToggle.setChecked(false);
                            applyListeners();
                        }
                    } else {
                        if (getApplication().getRunningShields().get(getControllerTag()) != null)
                            try {
                                if (((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview()) {
                                    facelogo.setVisibility(View.VISIBLE);
                                    ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(false);
                                }
                            } catch (RemoteException e) {
                                e.printStackTrace();
                                removeListeners();
                                cameraPreviewToggle.setChecked(true);
                                applyListeners();
                            }
                    }
                }
            }
        }, 500);

        try {
            ((FaceDetectionShield) getApplication().getRunningShields().get(
                    getControllerTag())).setCameraToPreview(((FaceDetectionShield) getApplication().getRunningShields().get(
                    getControllerTag())).isBackPreview());
            ((FaceDetectionShield) getApplication().getRunningShields().get(
                    getControllerTag())).invalidatePreview();
            ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(
                    ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).isFaceSelected());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        removeListeners();
        frontBackToggle.setChecked(((FaceDetectionShield) getApplication().getRunningShields().get(
                getControllerTag())).isBackPreview());
        applyListeners();
    }

    @Override
    public void doOnPause() {
        if (getApplication().getRunningShields().get(
                getControllerTag()) != null) {
            try {
                ((FaceDetectionShield) getApplication().getRunningShields().get(
                        getControllerTag())).hidePreview();

            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                facelogo.setVisibility(View.VISIBLE);
            }
        });
        if (getView() != null)
            getView().invalidate();
    }

    @Override
    public void onMenuClosed() {
        if (canChangeUI() && getView() != null && getApplication().getRunningShields().get(
                getControllerTag()) != null) {
            if (activity != null && activity.findViewById(R.id.isMenuOpening) != null) {
                if (((CheckBox) activity.findViewById(R.id.isMenuOpening)).isChecked() && cameraPreviewToggle.isChecked()) {
                    try {
                        if (getApplication().getRunningShields().get(getControllerTag()) != null)
                            if (((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).showPreview()) {
                                facelogo.setVisibility(View.INVISIBLE);
                                ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(true);
                            }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        removeListeners();
                        cameraPreviewToggle.setChecked(false);
                        applyListeners();
                    }
                } else {
                    if (getApplication().getRunningShields().get(getControllerTag()) != null)
                        try {
                            if (((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview()) {
                                facelogo.setVisibility(View.VISIBLE);
                                ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(false);
                            }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            removeListeners();
                            cameraPreviewToggle.setChecked(true);
                            applyListeners();
                        }
                }
            }
        }
    }

    @Override
    public void onChange(boolean isChecked) {
        if (canChangeUI() && getView() != null && getApplication().getRunningShields().get(
                getControllerTag()) != null) {
            if (activity != null && activity.findViewById(R.id.isMenuOpening) != null) {
                if (isChecked && !activity.isMenuOpened() && cameraPreviewToggle.isChecked()) {
                    try {
                        if (getApplication().getRunningShields().get(getControllerTag()) != null)
                            if (((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).showPreview()) {
                                facelogo.setVisibility(View.INVISIBLE);
                                ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(true);
                            }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        removeListeners();
                        cameraPreviewToggle.setChecked(false);
                        applyListeners();
                    }
                } else if (!isChecked || activity.isMenuOpened()) {
                    try {
                        if ((getApplication().getRunningShields().get(getControllerTag()) != null))
                            if (((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).hidePreview()) {
                                facelogo.setVisibility(View.VISIBLE);
                                ((FaceDetectionShield) getApplication().getRunningShields().get(getControllerTag())).setIsFaceSelected(false);
                            }
                        if (!isChecked && !activity.isMenuOpened()) {
                            removeListeners();
                            cameraPreviewToggle.setChecked(false);
                            applyListeners();
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        removeListeners();
                        cameraPreviewToggle.setChecked(true);
                        applyListeners();
                    }
                }
            }
        }
    }
} public class FacebookFragment extends ShieldFragmentParent<FacebookFragment> implements View.OnClickListener {

    LinearLayout lastPostTextCont;
    TextView userNameTextView;
    Button facebookLogin;
    Button facebookLogout;
    Bundle savedInstanceState;
    ProgressBar progress;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        setHasOptionsMenu(true);

        this.savedInstanceState = savedInstanceState;
        return inflater.inflate(R.layout.facebook_shield_fragment_layout,
                container, false);

    }

    @Override
    public void doOnStart() {
        initializeFirmata();
        checkLogin();
        facebookLogin.setOnClickListener(this);
        facebookLogout.setOnClickListener(this);
    }

    @Override
    public void doOnResume() {
        facebookLogin.setOnClickListener(this);
        facebookLogout.setOnClickListener(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (((FacebookShield) getApplication().getRunningShields().get(
                getControllerTag())).getCallbackManager() != null)
            ((FacebookShield) getApplication().getRunningShields().get(
                    getControllerTag())).getCallbackManager().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void doOnViewCreated(View v, @Nullable Bundle savedInstanceState) {
        lastPostTextCont = (LinearLayout) v.findViewById(R.id.postsCont);
        userNameTextView = (TextView) v
                .findViewById(R.id.facebook_shield_username_textview);
        facebookLogin = (Button) v.findViewById(R.id.login);
        facebookLogout = (Button) v.findViewById(R.id.logout);
        progress = (ProgressBar) v.findViewById(R.id.progress);
    }

    private FacebookEventHandler facebookEventHandler = new FacebookEventHandler() {

        @Override
        public void onRecievePost(final String post) {
            // TODO Auto-generated method stub
            if (canChangeUI()) {
                uiHandler.removeCallbacksAndMessages(null);
                uiHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        OneSheeldTextView posty = (OneSheeldTextView) activity
                                .getLayoutInflater().inflate(
                                        R.layout.facebook_post_item,
                                        lastPostTextCont, false);
                        posty.setText(post);
                        lastPostTextCont.addView(posty);
                        ((ScrollView) lastPostTextCont.getParent())
                                .invalidate();
                        Toast.makeText(activity, R.string.facebook_posted_on_your_wall_toast,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onFacebookLoggedIn() {
            // TODO Auto-generated method stub
            if (canChangeUI()) {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        buttonToLoggedIn();
                    }
                });
            }
        }

        @Override
        public void onFacebookError(final String error) {
            // TODO Auto-generated method stub
            if (canChangeUI()) {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Toast.makeText(activity, error, Toast.LENGTH_SHORT)
                                .show();
                        // buttonToLoggedIn();
                        // getAppActivity()
                        // .setSupportProgressBarIndeterminateVisibility(
                        // false);
                    }
                });
            }
        }

        @Override
        public void startProgress() {
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (progress != null && canChangeUI()) {
                        progress.setVisibility(View.VISIBLE);
                    }
                }
            });
        }

        @Override
        public void stopProgress() {
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (progress != null && canChangeUI()) {
                        progress.setVisibility(View.GONE);
                    }
                }
            });
        }

    };

    private void initializeFirmata() {
        if ((getApplication().getRunningShields().get(getControllerTag())) == null)
            getApplication().getRunningShields().put(
                    getControllerTag(),
                    new FacebookShield(activity, getControllerTag(), this,
                            savedInstanceState));
        ((FacebookShield) getApplication().getRunningShields().get(
                getControllerTag())).setShieldFragment(this);
        ((FacebookShield) getApplication().getRunningShields().get(
                getControllerTag()))
                .setFacebookEventHandler(facebookEventHandler);
        checkLogin();
    }

    private void checkLogin() {
        if ((getApplication().getRunningShields().get(getControllerTag())) != null
                && ((FacebookShield) getApplication().getRunningShields().get(
                getControllerTag())).isFacebookLoggedInAlready()) {
            buttonToLoggedIn();
        } else {
            buttonToLoggedOut();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super.onOptionsItemSelected(item);
    }

    private void logoutFromFacebook() {
        ((FacebookShield) getApplication().getRunningShields().get(
                getControllerTag())).logoutFromFacebook();
        buttonToLoggedOut();
    }

    private void loginToFacebook() {
        if (ConnectionDetector.isConnectingToInternet(activity))

            ((FacebookShield) getApplication().getRunningShields().get(
                    getControllerTag())).loginToFacebook();
        else
            Toast.makeText(getApplication().getApplicationContext(),
                    R.string.general_toasts_please_check_your_internet_connection_and_try_again_toast,
                    Toast.LENGTH_SHORT).show();
        // getAppActivity().setSupportProgressBarIndeterminateVisibility(true);
    }

    private void buttonToLoggedOut() {
        if (facebookLogout != null)
            facebookLogout.setVisibility(View.INVISIBLE);
        if (facebookLogin != null)
            facebookLogin.setVisibility(View.VISIBLE);
        if (userNameTextView != null)
            userNameTextView.setVisibility(View.INVISIBLE);
        if (lastPostTextCont != null) {
            lastPostTextCont.removeAllViews();
            lastPostTextCont.setVisibility(View.INVISIBLE);
        }
    }

    private void buttonToLoggedIn() {
        if (facebookLogin != null)
            facebookLogin.setVisibility(View.INVISIBLE);
        if (facebookLogout != null)
            facebookLogout.setVisibility(View.VISIBLE);
        if (userNameTextView != null)
            userNameTextView.setVisibility(View.VISIBLE);
        if (lastPostTextCont != null) {
            lastPostTextCont.removeAllViews();
            lastPostTextCont.setVisibility(View.VISIBLE);
        }
        userNameTextView.setText(activity.getString(R.string.facebook_logged_in_as)+": "
                + ((FacebookShield) getApplication().getRunningShields().get(
                getControllerTag())).getUsername());
    }

    @Override
    public void doOnServiceConnected() {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                loginToFacebook();
                break;
            case R.id.logout:
                logoutFromFacebook();
                break;
            default:
                break;
        }
    }
} public class GlcdFragment extends ShieldFragmentParent<GlcdFragment> {
    private GlcdView FragmentView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        FragmentView = new GlcdView(activity,GlcdShield.glcdWidth,GlcdShield.glcdHeight, getControllerTag());
        return FragmentView;
    }

    private GlcdShield.GlcdEventHandler glcdEventHandler = new GlcdShield.GlcdEventHandler() {
        @Override
        public void setView(GlcdView glcdView) {
            if (canChangeUI() && uiHandler != null) {
                FragmentView = glcdView;
            }
        }

        @Override
        public GlcdView getView() {
            return FragmentView;
        }

    };

    @Override
    public void doOnStart() {
        ((GlcdShield) getApplication().getRunningShields().get(getControllerTag())).setEventHandler(glcdEventHandler);
    }

    @Override
    public void doOnServiceConnected() {
        initializeFirmata();
    }

    private void initializeFirmata() {
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            getApplication().getRunningShields().put(getControllerTag(), new GlcdShield(activity, getControllerTag()));
        }
    }

    @Override
    public void doOnResume() {
        FragmentView.invalidate();
    }
} public class MusicPlayerFragment extends
        ShieldFragmentParent<MusicPlayerFragment> {
    SeekBar seekBar;
    TextView musicFileName, playingStatus;
    ImageView playingBtn;
    Thread seekBarTracker;
    private boolean isTracking = false;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        hasSettings = true;
        return inflater.inflate(R.layout.musicplayer_shield_fragment_layout,
                container, false);
    }

    @Override
    public void doOnStart() {
        activity.getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settingsViewContainer,
                        MusicShieldSettings.getInstance()).commit();
        startTracking();
    }

    private void stopTracking() {
        if (seekBarTracker != null && seekBarTracker.isAlive()) {
            isTracking = false;
            seekBarTracker.interrupt();
            seekBarTracker = null;
        }
    }

    private void startTracking() {
        stopTracking();
        isTracking = true;
        seekBarTracker = new Thread(new Runnable() {

            @Override
            public void run() {
                while (isTracking) {
                    if ((MusicShield) getApplication().getRunningShields().get(
                            getControllerTag()) != null
                            && ((MusicShield) getApplication()
                            .getRunningShields()
                            .get(getControllerTag())).mediaPlayer != null) {
                        seekBar.setMax(((MusicShield) getApplication()
                                .getRunningShields().get(getControllerTag())).mediaDuration);
                        try {
                            seekBar.setProgress(((MusicShield) getApplication()
                                    .getRunningShields()
                                    .get(getControllerTag())).mediaPlayer
                                    .getCurrentPosition());
                        } catch (IllegalStateException e) {
                        }
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        Log.e("TAG", "MusicPlayer::seekBarTracker", e);
                        break;
                    }

                }
            }
        });
        seekBarTracker.start();
    }

    @Override
    public void doOnResume() {
        MusicShield control = (MusicShield) getApplication()
                .getRunningShields().get(getControllerTag());
        if (control != null) {
            ((MusicShield) getApplication().getRunningShields().get(
                    getControllerTag())).setEventHandler(eventHandler);
            control = (MusicShield) getApplication().getRunningShields().get(
                    getControllerTag());
            if (control.mediaPlayer != null && control.mediaDuration > 0) {
                eventHandler.seekTo(control.mediaPlayer.getCurrentPosition()
                        * 100 / control.mediaDuration);
                eventHandler.setMusicName(control.musicFileName);
                if (control.mediaPlayer.isPlaying())
                    eventHandler.play();
                else
                    eventHandler.pause();
            } else {
                eventHandler.seekTo(0);
                eventHandler.pause();
                eventHandler.setMusicName("");
            }
        }
    }

    @Override
    public void doOnStop() {
        stopTracking();
    }

    MusicEventHandler eventHandler = new MusicEventHandler() {

        @Override
        public void setMusicName(final String name) {

            uiHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI())
                        musicFileName.setText(name);
                }
            });
        }

        @Override
        public void seekTo(final int pos) {
            uiHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI()) {
                        seekBar.setMax(((MusicShield) getApplication()
                                .getRunningShields().get(getControllerTag())).mediaDuration);
                        seekBar.setProgress(pos);
                    }
                }
            });
        }

        @Override
        public void play() {
            uiHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI()) {
                        playingBtn
                                .setBackgroundResource(R.drawable.musicplayer_play_symbol);
                        playingStatus.setText(R.string.music_player_playing);
                    }
                }
            });
        }

        @Override
        public void pause() {
            uiHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI()) {
                        playingBtn
                                .setBackgroundResource(R.drawable.musicplayer_pause_symbol);
                        playingStatus.setText(R.string.music_player_paused);
                    }
                }
            });
        }
    };

    @Override
    public void doOnViewCreated(View v, @Nullable Bundle savedInstanceState) {
        musicFileName = (TextView) v.findViewById(R.id.playingMusic);
        seekBar = (SeekBar) v.findViewById(R.id.seekBar);
        playingBtn = (ImageView) v.findViewById(R.id.playingBtn);
        playingStatus = (TextView) v.findViewById(R.id.playingStatus);
        hasSettings = true;
    }
} public class OrientationFragment extends
        ShieldFragmentParent<OrientationFragment> {
    TextView x, y, z;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.orientation_shield_fragment_layout,
                container, false);
    }

    @Override
    public void doOnStart() {
        ((OrientationShield) getApplication().getRunningShields().get(
                getControllerTag()))
                .setOrientationEventHandler(orientationEventHandler);
        ((OrientationShield) getApplication().getRunningShields().get(
                getControllerTag())).registerSensorListener(true);

    }

    @Override
    public void doOnViewCreated(View v, @Nullable Bundle savedInstanceState) {
        x = (TextView) v.findViewById(R.id.x_value_txt);
        y = (TextView) v.findViewById(R.id.y_value_txt);
        z = (TextView) v.findViewById(R.id.z_value_txt);
    }

    private OrientationEventHandler orientationEventHandler = new OrientationEventHandler() {

        @Override
        public void onSensorValueChangedFloat(final float[] value) {
            // TODO Auto-generated method stub

            // set data to UI
            x.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI())
                        x.setText("" + value[0]);
                }
            });
            y.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI())
                        y.setText("" + value[1]);
                }
            });
            z.post(new Runnable() {

                @Override
                public void run() {
                    if (canChangeUI())
                        z.setText("" + value[2]);

                }
            });
        }

        @Override
        public void isDeviceHasSensor(Boolean hasSensor) {
        }
    };

    private void initializeFirmata() {
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            getApplication().getRunningShields().put(getControllerTag(),
                    new OrientationShield(activity, getControllerTag()));

        }

    }

    public void doOnServiceConnected() {
        initializeFirmata();
    }
} public class SpeechRecognitionFragment extends
        ShieldFragmentParent<SpeechRecognitionFragment> {

    View statusCircle;
    OneSheeldTextView statusHint, recognizedResult;
    TextView rmsIndicator;
    RelativeLayout.LayoutParams params;
    int stepValue = 0;
    int marginValue;
    boolean isDetecting = false;
    String lastResult = "";

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.voice_recognition_shield_fragment_view,
                container, false);
    }

    @Override
    public void doOnViewCreated(View v, @Nullable Bundle savedInstanceState) {
        statusCircle = v.findViewById(R.id.statusCircle);
        statusHint = (OneSheeldTextView) v.findViewById(R.id.statusHint);
        rmsIndicator = (TextView) v.findViewById(R.id.rmsLevelIndicator);
        recognizedResult = (OneSheeldTextView) v
                .findViewById(R.id.recognizedResult);
        recognizedResult.setMovementMethod(new ScrollingMovementMethod());
        params = (LayoutParams) rmsIndicator.getLayoutParams();
        statusCircle.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {
                        if (stepValue == 0)
                            stepValue = statusCircle.getHeight() / 10;
                    }
                });
    }

    @Override
    public void doOnStart() {
        ((SpeechRecognitionShield) getApplication().getRunningShields().get(
                getControllerTag()))
                .setEventHandler(speechRecognitionEventHandler);
        lastResult = ((SpeechRecognitionShield) getApplication().getRunningShields()
                .get(getControllerTag())).getRecognized();
        recognizedResult.setText(lastResult.toLowerCase());
        statusCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (!isDetecting)
                    ((SpeechRecognitionShield) getApplication().getRunningShields()
                            .get(getControllerTag())).startRecognizer();
                else {
                    ((SpeechRecognitionShield) getApplication().getRunningShields()
                            .get(getControllerTag())).stopListening();
                    setOff();
                }
            }
        });
    }

    @Override
    public void doOnResume() {
        super.doOnResume();
        recognizedResult.setText(lastResult.toLowerCase());
        isDetecting =
                ((SpeechRecognitionShield) getApplication().getRunningShields()
                        .get(getControllerTag())).isWorking();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            lastResult = savedInstanceState.getString("lastResult");
            recognizedResult.setText(lastResult);
        }
    }

    private RecognitionEventHandler speechRecognitionEventHandler = new RecognitionEventHandler() {
        @Override
        public void onResult(final List<String> result) {
            if (canChangeUI())
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        setOff();
                        lastResult = result.get(0);
                        recognizedResult.setText(lastResult
                                .toLowerCase());
                    }
                });
        }

        @Override
        public void onReadyForSpeach(Bundle params) {
            if (canChangeUI())
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (canChangeUI()) {
                            lastResult = "";
                            recognizedResult.setText(lastResult);
                            setON();
                        }
                    }
                });
        }


        @Override
        public void onError(final String error, int errorCode) {
            if (canChangeUI())
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        setOff();
                        Toast.makeText(activity, error, Toast.LENGTH_SHORT)
                                .show();
                        lastResult = "";
                    }
                });
        }

        @Override
        public void onEndOfSpeech() {
            if (canChangeUI())
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        setOff();
                    }
                });
        }

        @Override
        public void onBeginningOfSpeech() {
            if (canChangeUI())
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        lastResult = "";
                        recognizedResult.setText(lastResult);
                        setON();
                    }
                });
        }

        @Override
        public void onRmsChanged(final float rmsdB) {
            if (canChangeUI())
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("RMS", rmsdB + "");
                        marginValue = (int) (stepValue * (rmsdB > 10 ? 10 : rmsdB));
                        params.bottomMargin = marginValue < 0 ? 0 : marginValue;
                        rmsIndicator.requestLayout();
                    }
                });
        }
    };

    private void setOff() {
        isDetecting = false;
        rmsIndicator.setVisibility(View.INVISIBLE);
        statusCircle.setBackgroundColor(getResources().getColor(
                R.color.voice_rec_circle_red));
        statusHint.setText(R.string.voice_recognizer_tap_to_speak_button);
    }

    private void setON() {
        isDetecting = true;
        rmsIndicator.setVisibility(View.VISIBLE);
        statusCircle.setBackgroundColor(getResources().getColor(
                R.color.voice_rec_circle_green));
        statusHint.setText(R.string.voice_recognizer_speak);
    }

    private void initializeFirmata() {
        if (getApplication().getRunningShields().get(getControllerTag()) == null) {
            getApplication().getRunningShields().put(getControllerTag(),
                    new SpeechRecognitionShield(activity, getControllerTag()));
        }

    }

    @Override
    public void doOnServiceConnected() {
        initializeFirmata();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("lastResult", lastResult);
    }
} public class TerminalFragment extends ShieldFragmentParent<TerminalFragment> {
    private ListView output;
    private OneSheeldEditText inputField;
    private OneSheeldButton send,copyAll;
    private boolean endedWithNewLine = false;
    private TerminalLinesAdapter outputAdapter;
    private ToggleButton timeToggle, autoScrollingToggle;

    public static String getTimeAsString() {
        return DateFormat.format("MM/dd/yyyy hh:mm:ss", new java.util.Date())
                .toString();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.terminal_shield_fragment_layout,
                container, false);
    }

    @Override
    public void doOnViewCreated(final View v, @Nullable Bundle savedInstanceState) {
        output = (ListView) v.findViewById(R.id.terminalOutput);
        outputAdapter = new TerminalLinesAdapter(activity,
                new ArrayList<TerminalPrintedLine>());
        output.setAdapter(outputAdapter);
        outputAdapter = (TerminalLinesAdapter) output.getAdapter();
        inputField = (OneSheeldEditText) v.findViewById(R.id.terminalInput);
        send = (OneSheeldButton) v.findViewById(R.id.send);
        timeToggle = (ToggleButton) v.findViewById(R.id.toggleTime);
        autoScrollingToggle = (ToggleButton) v
                .findViewById(R.id.toggleAutoScrolling);
        copyAll = (OneSheeldButton) v.findViewById(R.id.copy_all);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            copyAll.setVisibility(View.INVISIBLE);
        }
        timeToggle.setChecked(((TerminalShield) getApplication()
                .getRunningShields().get(getControllerTag())).isTimeOn);
        autoScrollingToggle.setChecked(((TerminalShield) getApplication()
                .getRunningShields().get(getControllerTag())).isAutoScrolling);
        timeToggle.setTypeface(getApplication().appFont);
        autoScrollingToggle.setTypeface(getApplication().appFont);
        timeToggle
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        ((TerminalShield) getApplication().getRunningShields()
                                .get(getControllerTag())).isTimeOn = isChecked;
                        outputAdapter.isTimeOn = isChecked;
                        if (!TerminalLinesAdapter.isTextSelected)
                            outputAdapter.notifyDataSetChanged();
                    }
                });
        autoScrollingToggle
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        ((TerminalShield) getApplication().getRunningShields()
                                .get(getControllerTag())).isAutoScrolling = isChecked;
                    }
                });
        v.findViewById(R.id.clearTerminal).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        outputAdapter
                                .updateLines(new ArrayList<TerminalPrintedLine>());
                        ((TerminalShield) getApplication().getRunningShields()
                                .get(getControllerTag())).lastItemEndedWithNewLine = true;
                        ((TerminalShield) getApplication().getRunningShields()
                                .get(getControllerTag())).tempLines = new CopyOnWriteArrayList<TerminalPrintedLine>();
                        ((TerminalShield) getApplication().getRunningShields()
                                .get(getControllerTag())).terminalPrintedLines = new CopyOnWriteArrayList<TerminalPrintedLine>();
                    }
                });
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ((TerminalShield) getApplication().getRunningShields().get(
                        getControllerTag())).input(inputField.getText()
                        .toString());
                ((TerminalShield) getApplication().getRunningShields().get(
                        getControllerTag())).terminalPrintedLines
                        .add(new TerminalPrintedLine((!endedWithNewLine ? "\n"
                                : "") + getTimeAsString() + " [TX] " + ": ",
                                inputField.getText().toString().getBytes(), true, false));
                ((TerminalShield) getApplication().getRunningShields().get(
                        getControllerTag())).tempLines
                        .add(new TerminalPrintedLine((!endedWithNewLine ? "\n"
                                : "") + getTimeAsString() + " [TX] " + ": ",
                                inputField.getText().toString().getBytes(), true, false));
                ((TerminalShield) getApplication().getRunningShields().get(
                        getControllerTag())).lastItemEndedWithNewLine = true;
                outputAdapter
                        .updateLines(((TerminalShield) getApplication()
                                .getRunningShields().get(getControllerTag())).tempLines);
                if (((TerminalShield) getApplication().getRunningShields().get(
                        getControllerTag())).tempLines.size() > 0
                        && ((TerminalShield) getApplication()
                        .getRunningShields().get(getControllerTag())).isAutoScrolling)
                    output.setSelection(((TerminalShield) getApplication()
                            .getRunningShields().get(getControllerTag())).tempLines
                            .size() - 1);
                endedWithNewLine = true;
                inputField.setText("");
                InputMethodManager imm = (InputMethodManager) activity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(inputField.getWindowToken(), 0);
            }
        });
        copyAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                outputAdapter.copyAll();
            }
        });

        int i = 0;
        for (final int id : ((TerminalShield) getApplication()
                .getRunningShields().get(getControllerTag())).encodingMths) {
            final int x = i;
            v.findViewById(id).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View vi) {
                    if (TerminalShield.selectedEnMth != x) {
                        v.findViewById(
                                ((TerminalShield) getApplication()
                                        .getRunningShields().get(
                                                getControllerTag())).encodingMths[TerminalShield.selectedEnMth])
                                .setBackgroundColor(
                                        getResources()
                                                .getColor(
                                                        R.color.arduino_conn_resetAll_bg));
                        v.findViewById(
                                ((TerminalShield) getApplication()
                                        .getRunningShields().get(
                                                getControllerTag())).encodingMths[x])
                                .setBackgroundColor(
                                        getResources().getColor(
                                                R.color.arduinoPinsSelector));
                        TerminalShield.selectedEnMth = x;
                        ((TerminalShield) getApplication().getRunningShields()
                                .get(getControllerTag())).tempLines = new CopyOnWriteArrayList<TerminalPrintedLine>();
                        for (TerminalPrintedLine line : ((TerminalShield) getApplication()
                                .getRunningShields().get(getControllerTag())).terminalPrintedLines) {
                            ((TerminalShield) getApplication()
                                    .getRunningShields()
                                    .get(getControllerTag())).tempLines
                                    .add(new TerminalPrintedLine(
                                            line.date,
                                            line.print,
                                            line.isEndedWithNewLine, line
                                            .isRx()));
                        }
                        outputAdapter
                                .updateLines(((TerminalShield) getApplication()
                                        .getRunningShields().get(
                                                getControllerTag())).tempLines);
                        if (((TerminalShield) getApplication()
                                .getRunningShields().get(getControllerTag())).tempLines
                                .size() > 0
                                && ((TerminalShield) getApplication()
                                .getRunningShields().get(
                                        getControllerTag())).isAutoScrolling)
                            output.setSelection(((TerminalShield) getApplication()
                                    .getRunningShields()
                                    .get(getControllerTag())).tempLines.size() - 1);
                    }
                }
            });
            i++;
        }
    }

    @Override
    public void doOnStart() {
        if (getView() != null) {
            getView().findViewById(
                    ((TerminalShield) getApplication().getRunningShields().get(
                            getControllerTag())).encodingMths[0])
                    .setBackgroundColor(
                            getResources().getColor(
                                    R.color.arduino_conn_resetAll_bg));
            getView().findViewById(
                    ((TerminalShield) getApplication().getRunningShields().get(
                            getControllerTag())).encodingMths[TerminalShield.selectedEnMth])
                    .setBackgroundColor(
                            getResources().getColor(R.color.arduinoPinsSelector));
        }
        ((TerminalShield) getApplication().getRunningShields().get(
                getControllerTag())).setEventHandler(terminalHandler);
        if (((TerminalShield) getApplication().getRunningShields().get(
                getControllerTag())).terminalPrintedLines == null)
            ((TerminalShield) getApplication().getRunningShields().get(
                    getControllerTag())).terminalPrintedLines = new CopyOnWriteArrayList<>();
        ((TerminalShield) getApplication().getRunningShields().get(
                getControllerTag())).tempLines = new CopyOnWriteArrayList<>();
        for (TerminalPrintedLine line : ((TerminalShield) getApplication()
                .getRunningShields().get(getControllerTag())).terminalPrintedLines) {
            ((TerminalShield) getApplication().getRunningShields().get(
                    getControllerTag())).tempLines.add(new TerminalPrintedLine(
                    line.date, line.print,
                    line.isEndedWithNewLine, line.isRx()));
        }
        outputAdapter.updateLines(((TerminalShield) getApplication()
                .getRunningShields().get(getControllerTag())).tempLines);
        if (((TerminalShield) getApplication().getRunningShields().get(
                getControllerTag())).tempLines.size() > 0
                && ((TerminalShield) getApplication().getRunningShields().get(
                getControllerTag())).isAutoScrolling)
            output.setSelection(((TerminalShield) getApplication()
                    .getRunningShields().get(getControllerTag())).tempLines
                    .size() - 1);
        outputAdapter.isTimeOn = ((TerminalShield) getApplication().getRunningShields().get(getControllerTag())).isTimeOn;
        if (!TerminalLinesAdapter.isTextSelected)
            outputAdapter.notifyDataSetChanged();
    }

    @Override
    public void doOnPause() {
        getAppActivity().hideSoftKeyboard();
    }

    TerminalHandler terminalHandler = new TerminalHandler() {
        @Override
        public void onPrint() {
            if (canChangeUI())
                uiHandler.post(new Runnable() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void run() {
                        if (output != null && canChangeUI()) {
                            outputAdapter
                                    .updateLines((List<TerminalPrintedLine>) ((TerminalShield) getApplication()
                                            .getRunningShields().get(
                                                    getControllerTag())).tempLines
                                            .clone());
                            if (((TerminalShield) getApplication()
                                    .getRunningShields().get(getControllerTag())).tempLines
                                    .size() > 0
                                    && ((TerminalShield) getApplication()
                                    .getRunningShields().get(
                                            getControllerTag())).isAutoScrolling)
                                output.setSelection(((TerminalShield) getApplication()
                                        .getRunningShields()
                                        .get(getControllerTag())).tempLines.size() - 1);
                        }
                    }
                });
        }
    };

} public class ToggleButtonFragment extends
        ShieldFragmentParent<ToggleButtonFragment> {
    OneSheeldToggleButton toggleButtonButton;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.toggle_button_shield_fragment_layout,
                container, false);

    }

    @Override
    public void doOnViewCreated(View v, @Nullable Bundle savedInstanceState) {
        toggleButtonButton = (OneSheeldToggleButton) v
                .findViewById(R.id.toggle_button_shield_button_toggle_button);
        if (getApplication().getRunningShields().get(
                getControllerTag()) == null) {
            getApplication().getRunningShields().put(getControllerTag(),
                    new ToggleButtonShield(activity, getControllerTag()));
        }
        toggleButtonButton
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        // TODO Auto-generated method stub
                        ((ToggleButtonShield) getApplication()
                                .getRunningShields().get(getControllerTag()))
                                .setButton(isChecked);

                    }
                });
        if (getApplication().getRunningShields().get(
                getControllerTag()) != null)
            toggleButtonButton.setEnabled(true);
    }

    @Override
    public void doOnStart() {
        toggleButtonButton.setChecked(((ToggleButtonShield) getApplication().getRunningShields().get(getControllerTag())).getButton());
        ConnectingPinsView.getInstance().reset(
                getApplication().getRunningShields().get(getControllerTag()),
                new OnPinSelectionListener() {

                    @Override
                    public void onSelect(ArduinoPin pin) {
                        if (pin != null) {
                            (getApplication()
                                    .getRunningShields()
                                    .get(getControllerTag()))
                                    .setConnected(new ArduinoConnectedPin(
                                            pin.microHardwarePin,
                                            OneSheeldDevice.OUTPUT));
                            ((ToggleButtonShield) getApplication().getRunningShields().get(getControllerTag())).setButton(toggleButtonButton.isChecked());
                            toggleButtonButton.setEnabled(true);
                        }

                    }

                    @Override
                    public void onUnSelect(ArduinoPin pin) {
                    }
                });

    }

}
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.analytics.HitBuilders;
import com.integreight.onesheeld.MainActivity;
import com.integreight.onesheeld.R;
import com.integreight.onesheeld.adapters.SelectedShieldsListAdapter;
import com.integreight.onesheeld.enums.UIShield;
import com.integreight.onesheeld.model.Shield;
import com.integreight.onesheeld.shields.ShieldFragmentParent;
import com.integreight.onesheeld.shields.fragments.AccelerometerFragment;
import com.integreight.onesheeld.shields.fragments.BuzzerFragment;
import com.integreight.onesheeld.shields.fragments.CameraFragment;
import com.integreight.onesheeld.shields.fragments.ClockFragment;
import com.integreight.onesheeld.shields.fragments.ColorDetectionFragment;
import com.integreight.onesheeld.shields.fragments.DataLoggerFragment;
import com.integreight.onesheeld.shields.fragments.EmailFragment;
import com.integreight.onesheeld.shields.fragments.EmptyShieldFragment;
import com.integreight.onesheeld.shields.fragments.FaceDetectionFragment;
import com.integreight.onesheeld.shields.fragments.FacebookFragment;
import com.integreight.onesheeld.shields.fragments.FoursquareFragment;
import com.integreight.onesheeld.shields.fragments.GamepadFragment;
import com.integreight.onesheeld.shields.fragments.GlcdFragment;
import com.integreight.onesheeld.shields.fragments.GpsFragment;
import com.integreight.onesheeld.shields.fragments.GravityFragment;
import com.integreight.onesheeld.shields.fragments.GyroscopeFragment;
import com.integreight.onesheeld.shields.fragments.InternetFragment;
import com.integreight.onesheeld.shields.fragments.KeyboardFragment;
import com.integreight.onesheeld.shields.fragments.KeypadFragment;
import com.integreight.onesheeld.shields.fragments.LcdFragment;
import com.integreight.onesheeld.shields.fragments.LedFragment;
import com.integreight.onesheeld.shields.fragments.LightFragment;
import com.integreight.onesheeld.shields.fragments.MagnetometerFragment;
import com.integreight.onesheeld.shields.fragments.MicFragment;
import com.integreight.onesheeld.shields.fragments.MusicPlayerFragment;
import com.integreight.onesheeld.shields.fragments.NfcFragment;
import com.integreight.onesheeld.shields.fragments.NotificationFragment;
import com.integreight.onesheeld.shields.fragments.OrientationFragment;
import com.integreight.onesheeld.shields.fragments.PatternFragment;
import com.integreight.onesheeld.shields.fragments.PhoneFragment;
import com.integreight.onesheeld.shields.fragments.PressureFragment;
import com.integreight.onesheeld.shields.fragments.ProximityFragment;
import com.integreight.onesheeld.shields.fragments.PushButtonFragment;
import com.integreight.onesheeld.shields.fragments.SevenSegmentFragment;
import com.integreight.onesheeld.shields.fragments.SkypeFragment;
import com.integreight.onesheeld.shields.fragments.SliderFragment;
import com.integreight.onesheeld.shields.fragments.SmsFragment;
import com.integreight.onesheeld.shields.fragments.SpeechRecognitionFragment;
import com.integreight.onesheeld.shields.fragments.TemperatureFragment;
import com.integreight.onesheeld.shields.fragments.TerminalFragment;
import com.integreight.onesheeld.shields.fragments.TextToSpeechFragment;
import com.integreight.onesheeld.shields.fragments.ToggleButtonFragment;
import com.integreight.onesheeld.shields.fragments.TwitterFragment;
import com.integreight.onesheeld.shields.fragments.VibrationFragment;
import com.integreight.onesheeld.utils.CrashlyticsUtils;
import com.integreight.onesheeld.utils.customviews.AppSlidingLeftMenu;
import com.integreight.onesheeld.utils.customviews.OneSheeldTextView;
import java.util.HashMap;
import java.util.Map;
package com.integreight.onesheeld.appFragments;




public class SelectedShieldsListFragment extends ListFragment {
    private static SelectedShieldsListAdapter UIShieldAdapter;
    Map<String, ShieldFragmentParent<?>> creadtedShields = new HashMap<>();
    private MainActivity activity;
    public int currentShield = 0;

    public static SelectedShieldsListFragment newInstance(Activity activity) {
        UIShieldAdapter = new SelectedShieldsListAdapter(activity);
        return new SelectedShieldsListFragment();
    }

    public static void renewUiShieldAdapter(Activity activity) {
        if (UIShieldAdapter != null)
            UIShieldAdapter.setActivity(activity);
        else {
            UIShieldAdapter = new SelectedShieldsListAdapter(activity);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        activity = (MainActivity) getActivity();
        if (UIShieldAdapter != null)
            UIShieldAdapter.setActivity(activity);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            this.activity = (MainActivity) context;
            renewUiShieldAdapter(activity);
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.selected_shields_list, null);
    }

    public ShieldFragmentParent<?> getShieldFragment(int position) {
        Shield uiShield = UIShieldAdapter.getItem(position);
        if (creadtedShields.containsKey(uiShield.tag))
            return creadtedShields.get(uiShield.tag);
        else {
            try {
                if (uiShield.shieldFragment != null)
                    return addToCreatedListAndReturn(uiShield, uiShield.shieldFragment.newInstance());
                else {
                    if (activity != null)
                        activity.getThisApplication()
                                .getTracker()
                                .send(new HitBuilders.EventBuilder()
                                        .setCategory("Extreme Cases")
                                        .setAction(
                                                "Initialize fragments without reflection")
                                        .build());
                    return generateShieldFragment(uiShield);
                }
            } catch (java.lang.InstantiationException e) {
                CrashlyticsUtils.logException(e);
                return generateShieldFragment(uiShield);
            } catch (IllegalAccessException e) {
                CrashlyticsUtils.logException(e);
                return generateShieldFragment(uiShield);
            }
        }
    }

    private ShieldFragmentParent<?> generateShieldFragment(Shield uiShield) {
        if (uiShield.id == UIShield.VIBRATION_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new VibrationFragment());
        if (uiShield.id == UIShield.LED_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new LedFragment());
        if (uiShield.id == UIShield.ACCELEROMETER_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield,
                    new AccelerometerFragment());
        if (uiShield.id == UIShield.FACEBOOK_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new FacebookFragment());
        if (uiShield.id == UIShield.KEYPAD_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new KeypadFragment());
        if (uiShield.id == UIShield.LCD_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new LcdFragment());
        if (uiShield.id == UIShield.MAGNETOMETER_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield,
                    new MagnetometerFragment());
        if (uiShield.id == UIShield.PUSHBUTTON_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new PushButtonFragment());
        if (uiShield.id == UIShield.SEVENSEGMENT_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield,
                    new SevenSegmentFragment());
        if (uiShield.id == UIShield.SLIDER_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new SliderFragment());
        if (uiShield.id == UIShield.BUZZER_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new BuzzerFragment());
        if (uiShield.id == UIShield.TOGGLEBUTTON_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield,
                    new ToggleButtonFragment());
        if (uiShield.id == UIShield.TWITTER_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new TwitterFragment());
        if (uiShield.id == UIShield.NOTIFICATION_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield,
                    new NotificationFragment());
        if (uiShield.id == UIShield.GAMEDPAD_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new GamepadFragment());
        if (uiShield.id == UIShield.FOURSQUARE_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new FoursquareFragment());
        if (uiShield.id == UIShield.GPS_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new GpsFragment());
        if (uiShield.id == UIShield.SMS_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield, new SmsFragment());
        if (uiShield.id == UIShield.MUSICPLAYER_SHIELD.getId())
            return addToCreatedListAndReturn(uiShield,
                    new MusicPlayerFragment());