public class MainActivity extends AppCompatActivity implements NegativeReviewListener, ReviewListener,
        DirectoryChooserFragment.OnFragmentInteractionListener {

    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;
    private static final int REQUEST_SELECT_PICTURE = 0x01;
    private static final String SAMPLE_CROPPED_IMAGE_NAME = "SampleCropImage.jpeg";

    public static Context sContext;
    public static Activity sActivity;

    public static BandClient client = null;
    public static boolean band2 = false;
    public static BandInfo[] devices;

    public static SharedPreferences sharedPreferences;
    public static SharedPreferences.Editor editor;

    public static BandSensorData bandSensorData;

    int base = 0;
    int r, g, b;
    Drawer result;
    int REQUEST_INVITE = 0;
    LibsConfiguration.LibsListener libsListener = new LibsConfiguration.LibsListener() {
        @Override
        public void onIconClicked(View v) {

        }

        @Override
        public boolean onLibraryAuthorClicked(View v, Library library) {
            return false;
        }

        @Override
        public boolean onLibraryContentClicked(View v, Library library) {
            return false;
        }

        @Override
        public boolean onLibraryBottomClicked(View v, Library library) {
            return false;
        }

        @Override
        public boolean onExtraClicked(View v, Libs.SpecialButton specialButton) {
            switch (v.getId()) {
                case R.id.aboutSpecial1:
                    startActivity(new Intent(MainActivity.this, ChangelogActivity.class));
                    return true;
            }
            return false;
        }

        @Override
        public boolean onIconLongClicked(View v) {
            return false;
        }

        @Override
        public boolean onLibraryAuthorLongClicked(View v, Library library) {
            return false;
        }

        @Override
        public boolean onLibraryContentLongClicked(View v, Library library) {
            return false;
        }

        @Override
        public boolean onLibraryBottomLongClicked(View v, Library library) {
            return false;
        }
    };
    IabHelper mHelper;
    String SKU_COKE = "cfb_coke", SKU_COFFEE = "cfb_coffee", SKU_BURGER = "cfb_burger",
            SKU_PIZZA = "cfb_pizza", SKU_MEAL = "cfb_meal";
    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
        public void onConsumeFinished(Purchase purchase, IabResult result) {
            if (mHelper == null) return;

            AlertDialog.Builder bld = new AlertDialog.Builder(getApplicationContext());
            bld.setNeutralButton("OK", null);
            if (result.isSuccess()) {
                bld.setMessage("Thank You");
                bld.create().show();
            } else {
                bld.setMessage(result.toString());
                bld.create().show();
            }
        }
    };
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
            if (mHelper == null) return;

            if (result.isFailure()) {
                AlertDialog.Builder bld = new AlertDialog.Builder(getApplicationContext());
                bld.setMessage("Error purchasing : " + result);
                bld.setNeutralButton("OK", null);
                bld.create().show();
                return;
            }

            if (purchase.getSku().equals(SKU_COKE)
                    || purchase.getSku().equals(SKU_COFFEE)
                    || purchase.getSku().equals(SKU_BURGER)
                    || purchase.getSku().equals(SKU_PIZZA)
                    || purchase.getSku().equals(SKU_MEAL)) {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            }
        }
    };
    private Switch logSwitch, backgroundLogSwitch;
    private TextView logStatus, backgroundLogStatus;
    private Tracker mTracker;
    private AlertDialog mAlertDialog;
    private Uri mDestinationUri;
    private DirectoryChooserFragment mDialog;

    public static void appendToUI(String string, String style) {
        Snackbar snackbar = Snackbar.make(sActivity.findViewById(R.id.main_content), string, Snackbar.LENGTH_SHORT);
        View view = snackbar.getView();
        switch (style) {
            case "Style.CONFIRM":
                view.setBackgroundColor(sContext.getResources().getColor(R.color.style_confirm));
                break;
            case "Style.INFO":
                view.setBackgroundColor(sContext.getResources().getColor(R.color.style_info));
                break;
            case "Style.ALERT":
                view.setBackgroundColor(sContext.getResources().getColor(R.color.style_alert));
                break;
        }
        snackbar.show();
    }

    @Override
    public void onNegativeReview(int stars) {
        StringBuilder emailBuilder = new StringBuilder();
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("mailto:pimplay69@gmail.com"));
        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.feedback) + " : " + getResources().getString(R.string.app_name));

        emailBuilder.append("\n \n \nOS Version: ").append(System.getProperty("os.version")).append("(").append(Build.VERSION.INCREMENTAL).append(")");
        emailBuilder.append("\nOS API Level: ").append(Build.VERSION.SDK_INT);
        emailBuilder.append("\nDevice: ").append(Build.DEVICE);
        emailBuilder.append("\nManufacturer: ").append(Build.MANUFACTURER);
        emailBuilder.append("\nModel (and Product): ").append(Build.MODEL).append(" (").append(Build.PRODUCT).append(")");
        PackageInfo appInfo = null;
        try {
            appInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        assert appInfo != null;
        emailBuilder.append("\nApp Version Name: ").append(appInfo.versionName);
        emailBuilder.append("\nApp Version Code: ").append(appInfo.versionCode);

        intent.putExtra(Intent.EXTRA_TEXT, emailBuilder.toString());
        startActivity(Intent.createChooser(intent, "Send via"));
    }

    @Override
    public void onReview(int stars) {
    }

    private boolean checkCameraPermission(boolean b) {
        int result;
        if (b)
            result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA);
        else
            result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        return result == PackageManager.PERMISSION_GRANTED;
    }

    private void requestCameraPermission(boolean b) {
        if (b) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.CAMERA)) {
                Toast.makeText(MainActivity.this, getString(R.string.camera_permission), Toast.LENGTH_LONG).show();
            } else {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.CAMERA}, 1);
            }
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(MainActivity.this, getString(R.string.storage_permission), Toast.LENGTH_LONG).show();
            } else {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, getString(R.string.camera_granted),
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, getString(R.string.camera_denied),
                            Toast.LENGTH_LONG).show();
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, getString(R.string.storage_granted),
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, getString(R.string.storage_denied),
                            Toast.LENGTH_LONG).show();
                }
                break;
        }
        switch (requestCode) {
            case REQUEST_STORAGE_READ_ACCESS_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    pickFromGallery();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sContext = getApplicationContext();
        sActivity = this;

        sharedPreferences = getApplicationContext().getSharedPreferences("MyPrefs", 0);
        editor = sharedPreferences.edit();

        bandSensorData = new BandSensorData();

        mDestinationUri = Uri.fromFile(new File(getCacheDir(), SAMPLE_CROPPED_IMAGE_NAME));

        SectionsPagerAdapter mSectionsPagerAdapter;
        ViewPager mViewPager;

        if (!checkCameraPermission(true))
            requestCameraPermission(true);
        if (!checkCameraPermission(false))
            requestCameraPermission(false);

        FiveStarsDialog fiveStarsDialog = new FiveStarsDialog(this, "pimplay69@gmail.com");
        fiveStarsDialog.setTitle(getString(R.string.rate_dialog_title))
                .setRateText(getString(R.string.rate_dialog_text))
                .setForceMode(false)
                .setUpperBound(4)
                .setNegativeReviewListener(this)
                .showAfter(5);

        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                String name;
                switch (position) {
                    case 0:
                        name = "THEME";
                        break;
                    case 1:
                        name = "SENSORS";
                        break;
                    case 2:
                        name = "EXTRAS";
                        break;
                    default:
                        name = "CfB";
                }

                mTracker.setScreenName("Image~" + name);
                mTracker.send(new HitBuilders.ScreenViewBuilder().build());

                logSwitch = (Switch) findViewById(R.id.log_switch);
                backgroundLogSwitch = (Switch) findViewById(R.id.backlog_switch);
                logStatus = (TextView) findViewById(R.id.logStatus);
                backgroundLogStatus = (TextView) findViewById(R.id.backlogStatus);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        Drawable headerBackground = null;
        String encoded = sharedPreferences.getString("me_tile_image", "null");
        if (!encoded.equals("null")) {
            byte[] imageAsBytes = Base64.decode(encoded.getBytes(), Base64.DEFAULT);
            headerBackground = new BitmapDrawable(BitmapFactory
                    .decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
        }

        AccountHeader accountHeader = new AccountHeaderBuilder().withActivity(this)
                .withCompactStyle(true)
                .withHeaderBackground((headerBackground == null) ?
                        getResources().getDrawable(R.drawable.pipboy) : headerBackground)
                .addProfiles(
                        new ProfileDrawerItem().withName(sharedPreferences.getString("device_name", "Companion For Band"))
                                .withEmail(sharedPreferences.getString("device_mac", "pimplay69@gmail.com"))
                                .withIcon(getResources().getDrawable(R.drawable.band))
                )
                .build();

        result = new DrawerBuilder()
                .withActivity(this)
                .withToolbar(toolbar)
                .withActionBarDrawerToggleAnimated(true)
                .withAccountHeader(accountHeader)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName(getString(R.string.drawer_cloud)).withIcon(GoogleMaterial.Icon.gmd_cloud).withIdentifier(1),
                        new DividerDrawerItem(),
                        new PrimaryDrawerItem().withName(getString(R.string.rate)).withIcon(GoogleMaterial.Icon.gmd_rate_review).withIdentifier(2),
                        new PrimaryDrawerItem().withName(getString(R.string.feedback)).withIcon(GoogleMaterial.Icon.gmd_feedback).withIdentifier(3),
                        new DividerDrawerItem(),
                        new PrimaryDrawerItem().withName(getString(R.string.share)).withIcon(GoogleMaterial.Icon.gmd_share).withIdentifier(4),
                        new PrimaryDrawerItem().withName(getString(R.string.other)).withIcon(GoogleMaterial.Icon.gmd_apps).withIdentifier(5),
                        new DividerDrawerItem(),
                        new PrimaryDrawerItem().withName(getString(R.string.report)).withIcon(GoogleMaterial.Icon.gmd_bug_report).withIdentifier(6),
                        new PrimaryDrawerItem().withName(getString(R.string.translate)).withIcon(GoogleMaterial.Icon.gmd_translate).withIdentifier(9),
                        new DividerDrawerItem(),
                        new PrimaryDrawerItem().withName(getString(R.string.support)).withIcon(GoogleMaterial.Icon.gmd_attach_money).withIdentifier(7),
                        new PrimaryDrawerItem().withName(getString(R.string.aboutLib)).withIcon(GoogleMaterial.Icon.gmd_info).withIdentifier(8)
                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        boolean flag;
                        if (drawerItem != null) {
                            flag = true;
                            switch ((int) drawerItem.getIdentifier()) {
                                case 1:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Cloud")
                                            .build());

                                    if (!sharedPreferences.getString("access_token", "hi").equals("hi"))
                                        startActivity(new Intent(getApplicationContext(), CloudActivity.class));
                                    else
                                        startActivity(new Intent(getApplicationContext(), WebviewActivity.class));
                                    break;
                                case 2:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Rate and Review")
                                            .build());
                                    String MARKET_URL = "https://play.google.com/store/apps/details?id=";
                                    String PlayStoreListing = getPackageName();
                                    Intent rate = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URL + PlayStoreListing));
                                    startActivity(rate);
                                    break;
                                case 3:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Feedback")
                                            .build());
                                    final StringBuilder emailBuilder = new StringBuilder();
                                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("mailto:pimplay69@gmail.com"));
                                    intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name));

                                    emailBuilder.append("\n \n \nOS Version: ").append(System.getProperty("os.version")).append("(").append(Build.VERSION.INCREMENTAL).append(")");
                                    emailBuilder.append("\nOS API Level: ").append(Build.VERSION.SDK_INT);
                                    emailBuilder.append("\nDevice: ").append(Build.DEVICE);
                                    emailBuilder.append("\nManufacturer: ").append(Build.MANUFACTURER);
                                    emailBuilder.append("\nModel (and Product): ").append(Build.MODEL).append(" (").append(Build.PRODUCT).append(")");
                                    PackageInfo appInfo = null;
                                    try {
                                        appInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                                    } catch (PackageManager.NameNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    assert appInfo != null;
                                    emailBuilder.append("\nApp Version Name: ").append(appInfo.versionName);
                                    emailBuilder.append("\nApp Version Code: ").append(appInfo.versionCode);

                                    intent.putExtra(Intent.EXTRA_TEXT, emailBuilder.toString());
                                    startActivity(Intent.createChooser(intent, "Send via"));
                                    break;
                                case 4:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Share")
                                            .build());
                                    Intent i = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title))
                                            .setMessage(getString(R.string.invitation_message))
                                            .setCallToActionText(getString(R.string.invitation_cta))
                                            .build();
                                    startActivityForResult(i, REQUEST_INVITE);
                                    break;
                                case 5:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Other Apps")
                                            .build());
                                    String PlayStoreDevAccount = "https://play.google.com/store/apps/developer?id=P.I.M.P.";
                                    Intent devPlay = new Intent(Intent.ACTION_VIEW, Uri.parse(PlayStoreDevAccount));
                                    startActivity(devPlay);
                                    break;
                                case 6:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Report Bugs")
                                            .build());
                                    startActivity(new Intent(MainActivity.this, GittyActivity.class));
                                    break;
                                case 7:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Donate")
                                            .build());

                                    String base64EncodedPublicKey = getString(R.string.base64);
                                    mHelper = new IabHelper(getApplicationContext(), base64EncodedPublicKey);
                                    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
                                        public void onIabSetupFinished(IabResult result) {
                                            if (!result.isSuccess()) {
                                                Toast.makeText(MainActivity.this,
                                                        "Problem setting up In-app Billing: " + result,
                                                        Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    });

                                    final Dialog dialog = new Dialog(MainActivity.this);
                                    dialog.setContentView(R.layout.dialog_donate);
                                    dialog.setTitle("Donate");

                                    String[] title = {"Coke", "Coffee", "Burger", "Pizza", "Meal"};
                                    String[] price = {"Rs. 10.00", "Rs. 50.00", "Rs. 100.00", "Rs. 500.00", "Rs. 1,000.00"};

                                    ListView listView = (ListView) dialog.findViewById(R.id.list);
                                    listView.setAdapter(new DonateListAdapter(MainActivity.this, title, price));
                                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            switch (position) {
                                                case 0:
                                                    mHelper.launchPurchaseFlow(MainActivity.this, SKU_COKE, 1, mPurchaseFinishedListener, "payload");
                                                    break;
                                                case 1:
                                                    mHelper.launchPurchaseFlow(MainActivity.this, SKU_COFFEE, 1, mPurchaseFinishedListener, "payload");
                                                    break;
                                                case 2:
                                                    mHelper.launchPurchaseFlow(MainActivity.this, SKU_BURGER, 1, mPurchaseFinishedListener, "payload");
                                                    break;
                                                case 3:
                                                    mHelper.launchPurchaseFlow(MainActivity.this, SKU_PIZZA, 1, mPurchaseFinishedListener, "payload");
                                                    break;
                                                case 4:
                                                    mHelper.launchPurchaseFlow(MainActivity.this, SKU_MEAL, 1, mPurchaseFinishedListener, "payload");
                                                    break;
                                            }
                                        }
                                    });

                                    dialog.show();
                                    break;
                                case 8:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("About")
                                            .build());
                                    new LibsBuilder()
                                            .withLicenseShown(true)
                                            .withVersionShown(true)
                                            .withActivityStyle(Libs.ActivityStyle.DARK)
                                            .withAboutVersionShown(true)
                                            .withActivityTitle(getString(R.string.app_name))
                                            .withAboutIconShown(true)
                                            .withListener(libsListener)
                                            .start(MainActivity.this);
                                    break;
                                case 9:
                                    mTracker.send(new HitBuilders.EventBuilder()
                                            .setCategory("Action")
                                            .setAction("Translate")
                                            .build());
                                    Intent translate = new Intent(Intent.ACTION_VIEW,
                                            Uri.parse("https://poeditor.com/join/project/AZQxDV2440"));
                                    startActivity(translate);
                                    break;
                                default:
                                    break;
                            }
                        } else {
                            flag = false;
                        }
                        return flag;
                    }
                })
                .withSavedInstance(savedInstanceState)
                .build();

        AppUpdater appUpdater = new AppUpdater(this);
        appUpdater.start();

        final DirectoryChooserConfig config = DirectoryChooserConfig.builder()
                .allowNewDirectoryNameModification(true)
                .newDirectoryName("CfBCamera")
                .initialDirectory(sharedPreferences.getString("pic_location", "/storage/emulated/0/CompanionForBand/Camera"))
                .build();
        mDialog = DirectoryChooserFragment.newInstance(config);

        new BandUtils().execute();

        CustomActivityOnCrash.install(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INVITE) {
            if (resultCode != -1) {
                Toast.makeText(MainActivity.this, getString(R.string.send_failed), Toast.LENGTH_LONG).show();
            }
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_SELECT_PICTURE) {
                final Uri selectedUri = data.getData();
                if (selectedUri != null) {
                    startCropActivity(data.getData());
                } else {
                    Toast.makeText(MainActivity.this, R.string.toast_cannot_retrieve_selected_image, Toast.LENGTH_SHORT).show();
                }
            } else if (requestCode == UCrop.REQUEST_CROP) {
                handleCropResult(data);
            }
        }
        if (resultCode == UCrop.RESULT_ERROR) {
            handleCropError(data);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("CfB", "Setting screen name: " + "MAIN");
        mTracker.setScreenName("Image~" + "MAIN");
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }

    public void ButtonClick(View view) {
        switch (view.getId()) {
            case R.id.base:
                pickColor("base", view.getId());
                break;
            case R.id.highlight:
                pickColor("highLight", view.getId());
                break;
            case R.id.lowlight:
                pickColor("lowLight", view.getId());
                break;
            case R.id.secondaryText:
                pickColor("secondaryText", view.getId());
                break;
            case R.id.highContrast:
                pickColor("highContrast", view.getId());
                break;
            case R.id.muted:
                pickColor("muted", view.getId());
                break;
        }
    }

    void pickColor(final String string, final int id) {
        base = sharedPreferences.getInt(string, -16777216);
        r = (base >> 16 & 0xFF);
        g = (base >> 8 & 0xFF);
        b = (base & 0xFF);
        final ColorPicker colorPicker = new ColorPicker(MainActivity.this, r, g, b);
        colorPicker.show();
        Button okColor = (Button) colorPicker.findViewById(R.id.okColorButton);
        okColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putInt(string, colorPicker.getColor());
                editor.apply();
                findViewById(id).setBackgroundColor(colorPicker.getColor());
                colorPicker.dismiss();
            }
        });
    }

    public void SwitchClick(View view) {
        switch (view.getId()) {
            case R.id.log_switch:
                setSwitch(logSwitch, logStatus, "log");
                if (logSwitch.isChecked())
                    backgroundLogSwitch.setVisibility(View.VISIBLE);
                else {
                    backgroundLogSwitch.setChecked(false);
                    setSwitch(backgroundLogSwitch, backgroundLogStatus, "backlog");
                    backgroundLogSwitch.setVisibility(View.GONE);
                }
                break;
            case R.id.backlog_switch:
                setSwitch(backgroundLogSwitch, backgroundLogStatus, "backlog");
                break;
        }
    }

    void setSwitch(Switch s, TextView textView, String string) {
        if (!s.isChecked()) {
            editor.putBoolean(string, false);
            editor.apply();
            textView.setVisibility(View.GONE);
        } else {
            editor.putBoolean(string, true);
            editor.apply();
            textView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        if (client != null) {
            try {
                client.disconnect().await();
            } catch (Exception e) {
                // Do nothing as this is happening during destroy
            }
        }
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mAlertDialog != null && mAlertDialog.isShowing()) {
            mAlertDialog.dismiss();
        }
    }

    protected void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            showAlertDialog(getString(R.string.permission_title_rationale), rationale,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{permission}, requestCode);
                        }
                    }, getString(R.string.label_ok), null, getString(R.string.label_cancel));
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    protected void showAlertDialog(@Nullable String title, @Nullable String message,
                                   @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                                   @NonNull String positiveText,
                                   @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                                   @NonNull String negativeText) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
        mAlertDialog = builder.show();
    }

    private void pickFromGallery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.permission_read_storage_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(intent, getString(R.string.label_select_picture)), REQUEST_SELECT_PICTURE);
        }
    }

    private void startCropActivity(@NonNull Uri uri) {
        UCrop uCrop = UCrop.of(uri, mDestinationUri);
        if (band2) uCrop.withAspectRatio(310, 128);
        else uCrop.withAspectRatio(310, 102);
        uCrop.start(MainActivity.this);
    }

    private void handleCropResult(@NonNull Intent result) {
        final Uri resultUri = UCrop.getOutput(result);
        if (resultUri != null) {
            ((ImageView) findViewById(R.id.selected_me_tile_image_view)).setImageURI(resultUri);
        } else {
            Toast.makeText(MainActivity.this, R.string.toast_cannot_retrieve_cropped_image, Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    private void handleCropError(@NonNull Intent result) {
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            Toast.makeText(MainActivity.this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MainActivity.this, R.string.toast_unexpected_error, Toast.LENGTH_SHORT).show();
        }
    }

    public void CropClick(View view) {
        pickFromGallery();
    }

    public void changePictureLocation(View view) {
        mDialog.show(getFragmentManager(), null);
    }

    @Override
    public void onSelectDirectory(@NonNull String path) {
        editor.putString("pic_location", path);
        editor.apply();
        mDialog.dismiss();
    }

    @Override
    public void onCancelChooser() {
        mDialog.dismiss();
    }
} public class AccelerometerEventListener implements BandAccelerometerEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandAccelerometerChanged(final BandAccelerometerEvent event) {
        if (event != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add(event.getAccelerationX());
                    }
                });

            SensorsFragment.appendToUI(String.format(" X = %.3f (m/s²) \n Y = %.3f (m/s²)\n Z = %.3f (m/s²)",
                    event.getAccelerationX(),
                    event.getAccelerationY(),
                    event.getAccelerationZ()), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setAccelerometerData(event);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Accelerometer");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Accelerometer" + File.separator + "Accelerometer_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Accelerometer" + File.separator + "Accelerometer_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()),
                                    str, String.valueOf(event.getAccelerationX()),
                                    String.valueOf(event.getAccelerationY()),
                                    String.valueOf(event.getAccelerationZ())});

                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Accelerometer" + File.separator + "Accelerometer_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), "X", "Y", "Z"});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        Log.e("CSV", e.toString());
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class AllSensorsAccelerometerEventListener implements BandAccelerometerEventListener {

    @Override
    public void onBandAccelerometerChanged(final BandAccelerometerEvent event) {
        if (event != null) {
            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                String folderPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + "CompanionForBand" + File.separator + "All-in-One";
                File file = new File(folderPath);
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String filePath = folderPath + File.separator + "All-in-One_"
                                + DateFormat.getDateInstance().format(date) + ".csv";
                        if (new File(filePath).exists()) {
                            String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(filePath, true));
                            if (MainActivity.band2) {
                                csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()), str,
                                        String.valueOf(MainActivity.bandSensorData.getAccelerometerData().getAccelerationX()),
                                        String.valueOf(MainActivity.bandSensorData.getAccelerometerData().getAccelerationY()),
                                        String.valueOf(MainActivity.bandSensorData.getAccelerometerData().getAccelerationZ()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getTotalGainToday()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getTotalGain()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getTotalLoss()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getSteppingGain()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getSteppingLoss()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getStepsAscended()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getStepsDescended()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getRate()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getFlightsAscendedToday()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getFlightsAscended()),
                                        String.valueOf(MainActivity.bandSensorData.getAltimeterData().getFlightsDescended()),
                                        String.valueOf(MainActivity.bandSensorData.getAmbientLightData().getBrightness()),
                                        String.valueOf(MainActivity.bandSensorData.getBarometerData().getAirPressure()),
                                        String.valueOf(MainActivity.bandSensorData.getBarometerData().getTemperature()),
                                        String.valueOf(MainActivity.bandSensorData.getCalorieData().getCaloriesToday()),
                                        String.valueOf(MainActivity.bandSensorData.getCalorieData().getCalories()),
                                        String.valueOf(MainActivity.bandSensorData.getContactData().getContactState()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getMotionType()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getPace()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getSpeed()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getDistanceToday()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getTotalDistance()),
                                        String.valueOf(MainActivity.bandSensorData.getGsrData().getResistance()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAccelerationX()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAccelerationY()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAccelerationZ()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAngularVelocityX()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAngularVelocityY()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAngularVelocityZ()),
                                        String.valueOf(MainActivity.bandSensorData.getHeartRateData().getHeartRate()),
                                        String.valueOf(MainActivity.bandSensorData.getHeartRateData().getQuality()),
                                        String.valueOf(MainActivity.bandSensorData.getPedometerData().getStepsToday()),
                                        String.valueOf(MainActivity.bandSensorData.getPedometerData().getTotalSteps()),
                                        String.valueOf(MainActivity.bandSensorData.getRrIntervalData().getInterval()),
                                        String.valueOf(MainActivity.bandSensorData.getSkinTemperatureData().getTemperature()),
                                        String.valueOf(MainActivity.bandSensorData.getUvIndexData().getUVExposureToday()),
                                        String.valueOf(MainActivity.bandSensorData.getUvIndexData().getUVIndexLevel())});
                            } else {
                                csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()), str,
                                        String.valueOf(MainActivity.bandSensorData.getAccelerometerData().getAccelerationX()),
                                        String.valueOf(MainActivity.bandSensorData.getAccelerometerData().getAccelerationY()),
                                        String.valueOf(MainActivity.bandSensorData.getAccelerometerData().getAccelerationZ()),
                                        "Band 2 only", "Band 2 only", "Band 2 only", "Band 2 only", "Band 2 only",
                                        "Band 2 only", "Band 2 only", "Band 2 only", "Band 2 only", "Band 2 only",
                                        "Band 2 only", "Band 2 only", "Band 2 only", "Band 2 only", "Band 2 only",
                                        String.valueOf(MainActivity.bandSensorData.getCalorieData().getCalories()),
                                        String.valueOf(MainActivity.bandSensorData.getContactData().getContactState()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getMotionType()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getPace()),
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getSpeed()),
                                        "Band 2 only",
                                        String.valueOf(MainActivity.bandSensorData.getDistanceData().getTotalDistance()),
                                        "Band 2 only",
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAccelerationX()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAccelerationY()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAccelerationZ()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAngularVelocityX()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAngularVelocityY()),
                                        String.valueOf(MainActivity.bandSensorData.getGyroscopeData().getAngularVelocityZ()),
                                        String.valueOf(MainActivity.bandSensorData.getHeartRateData().getHeartRate()),
                                        String.valueOf(MainActivity.bandSensorData.getHeartRateData().getQuality()),
                                        "Band 2 only",
                                        String.valueOf(MainActivity.bandSensorData.getPedometerData().getTotalSteps()),
                                        "Band 2 only",
                                        String.valueOf(MainActivity.bandSensorData.getSkinTemperatureData().getTemperature()),
                                        "Band 2 only",
                                        String.valueOf(MainActivity.bandSensorData.getUvIndexData().getUVIndexLevel())});
                            }
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(filePath, true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp),
                                    MainActivity.sContext.getString(R.string.date_time), "X", "Y", "Z",
                                    MainActivity.sContext.getString(R.string.total_gain_today),
                                    MainActivity.sContext.getString(R.string.total_gain),
                                    MainActivity.sContext.getString(R.string.total_loss),
                                    MainActivity.sContext.getString(R.string.stepping_gain),
                                    MainActivity.sContext.getString(R.string.stepping_loss),
                                    MainActivity.sContext.getString(R.string.steps_ascended),
                                    MainActivity.sContext.getString(R.string.steps_descended),
                                    MainActivity.sContext.getString(R.string.alt_rate),
                                    MainActivity.sContext.getString(R.string.stairs_ascended_today),
                                    MainActivity.sContext.getString(R.string.stairs_ascended),
                                    MainActivity.sContext.getString(R.string.stairs_descended),
                                    MainActivity.sContext.getString(R.string.brightness),
                                    MainActivity.sContext.getString(R.string.air_pressure),
                                    MainActivity.sContext.getString(R.string.air_temperature),
                                    MainActivity.sContext.getString(R.string.calories_today),
                                    MainActivity.sContext.getString(R.string.calories),
                                    MainActivity.sContext.getString(R.string.contact_status),
                                    MainActivity.sContext.getString(R.string.motion_type),
                                    MainActivity.sContext.getString(R.string.pace),
                                    MainActivity.sContext.getString(R.string.speed),
                                    MainActivity.sContext.getString(R.string.distance_today),
                                    MainActivity.sContext.getString(R.string.total_distance),
                                    MainActivity.sContext.getString(R.string.resistance),
                                    "X m/s²", "Y", "Z", "X °/sec", "Y", "Z",
                                    MainActivity.sContext.getString(R.string.heart_rate),
                                    MainActivity.sContext.getString(R.string.quality),
                                    MainActivity.sContext.getString(R.string.steps_today),
                                    MainActivity.sContext.getString(R.string.total_steps),
                                    MainActivity.sContext.getString(R.string.rr),
                                    MainActivity.sContext.getString(R.string.temperature),
                                    MainActivity.sContext.getString(R.string.uv_today),
                                    MainActivity.sContext.getString(R.string.uv_index)});
                            csvWriter.close();
                        }
                    } catch (Exception e) {
                        Log.e("All-in-One CSV", e.toString());
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class AltimeterEventListener implements BandAltimeterEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandAltimeterChanged(final BandAltimeterEvent event) {
        if (event != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add(event.getRate());
                    }
                });

            try {
                SensorsFragment.appendToUI(new StringBuilder()
                                .append(MainActivity.sContext.getString(R.string.total_gain_today))
                                .append(String.format(" = %d cm\n", event.getTotalGainToday()))
                                .append(MainActivity.sContext.getString(R.string.total_gain))
                                .append(String.format(" = %d cm\n", event.getTotalGain()))
                                .append(MainActivity.sContext.getString(R.string.total_loss))
                                .append(String.format(" = %d cm\n", event.getTotalLoss()))
                                .append(MainActivity.sContext.getString(R.string.stepping_gain))
                                .append(String.format(" = %d cm\n", event.getSteppingGain()))
                                .append(MainActivity.sContext.getString(R.string.stepping_loss))
                                .append(String.format(" = %d cm\n", event.getSteppingLoss()))
                                .append(MainActivity.sContext.getString(R.string.steps_ascended))
                                .append(String.format(" = %d\n", event.getStepsAscended()))
                                .append(MainActivity.sContext.getString(R.string.steps_descended))
                                .append(String.format(" = %d\n", event.getStepsDescended()))
                                .append(MainActivity.sContext.getString(R.string.alt_rate))
                                .append(String.format(" = %f cm/s\n", event.getRate()))
                                .append(MainActivity.sContext.getString(R.string.stairs_ascended_today))
                                .append(String.format(" = %d\n", event.getFlightsAscendedToday()))
                                .append(MainActivity.sContext.getString(R.string.stairs_ascended))
                                .append(String.format(" = %d\n", event.getFlightsAscended()))
                                .append(MainActivity.sContext.getString(R.string.stairs_descended))
                                .append(String.format(" = %d\n", event.getFlightsDescended())).toString()
                        , textView);

                if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                    MainActivity.bandSensorData.setAltimeterData(event);

                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Altimeter");
                    if (file.exists() || file.isDirectory()) {
                        try {
                            Date date = new Date();
                            String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                            if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Altimeter" + File.separator + "Altimeter_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                                String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                                CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Altimeter" + File.separator + "Altimeter_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                                csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()), str,
                                        String.valueOf(event.getTotalGainToday()),
                                        String.valueOf(event.getTotalGain()),
                                        String.valueOf(event.getTotalLoss()),
                                        String.valueOf(event.getSteppingGain()),
                                        String.valueOf(event.getSteppingLoss()),
                                        String.valueOf(event.getStepsAscended()),
                                        String.valueOf(event.getStepsDescended()),
                                        String.valueOf(event.getRate()),
                                        String.valueOf(event.getFlightsAscendedToday()),
                                        String.valueOf(event.getFlightsAscended()),
                                        String.valueOf(event.getFlightsDescended())});
                                csvWriter.close();
                            } else {
                                CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Altimeter" + File.separator + "Altimeter_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.total_gain_today),
                                        MainActivity.sContext.getString(R.string.total_gain), MainActivity.sContext.getString(R.string.total_loss), MainActivity.sContext.getString(R.string.stepping_gain),
                                        MainActivity.sContext.getString(R.string.stepping_loss), MainActivity.sContext.getString(R.string.steps_ascended), MainActivity.sContext.getString(R.string.steps_descended),
                                        MainActivity.sContext.getString(R.string.alt_rate), MainActivity.sContext.getString(R.string.stairs_ascended_today), MainActivity.sContext.getString(R.string.stairs_ascended), MainActivity.sContext.getString(R.string.stairs_descended)});
                                csvWriter.close();
                            }
                        } catch (IOException e) {
                            Log.e("CSV", e.toString());
                        }
                    } else {
                        file.mkdirs();
                    }
                }
            } catch (Exception e) {
                SensorsFragment.appendToUI(e.toString(), textView);
            }
        }
    }
} public class AmbientLightEventListener implements BandAmbientLightEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandAmbientLightChanged(final BandAmbientLightEvent event) {
        if (event != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add((float) event.getBrightness());
                    }
                });

            SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.brightness)
                    + String.format(" = %d lux\n", event.getBrightness()), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setAmbientLightData(event);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "AmbientLight");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "AmbientLight" + File.separator + "AmbientLight_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "AmbientLight" + File.separator + "AmbientLight_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()),
                                    str, String.valueOf(event.getBrightness())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "AmbientLight" + File.separator + "AmbientLight_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.brightness)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        Log.e("CSV", e.toString());
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class BarometerEventListener implements BandBarometerEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandBarometerChanged(final BandBarometerEvent event) {
        if (event != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add((float) event.getAirPressure());
                    }
                });

            SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.air_pressure)
                    + String.format(" = %.3f hPa\n", event.getAirPressure())
                    + MainActivity.sContext.getString(R.string.air_temperature)
                    + String.format(" = %.2f °C = %.2f F",
                    event.getTemperature(), 1.8 * event.getTemperature() + 32), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setBarometerData(event);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Barometer");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Barometer" + File.separator + "Barometer_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Barometer" + File.separator + "Barometer_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()),
                                    str, String.valueOf(event.getAirPressure()),
                                    String.valueOf(event.getTemperature())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Barometer" + File.separator + "Barometer_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.air_pressure), MainActivity.sContext.getString(R.string.air_temperature)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class CaloriesEventListener implements BandCaloriesEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandCaloriesChanged(final BandCaloriesEvent bandCaloriesEvent) {
        if (bandCaloriesEvent != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add((float) bandCaloriesEvent.getCalories());
                    }
                });

            if (MainActivity.band2) {
                try {
                    SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.calories_today) + " = " + bandCaloriesEvent.getCaloriesToday() + " kCal\n" +
                            MainActivity.sContext.getString(R.string.calories) + " = " + bandCaloriesEvent.getCalories() + " kCal", textView);
                } catch (Exception e) {
                    SensorsFragment.appendToUI(e.toString(), textView);
                }
            } else {
                SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.calories) + " = " + bandCaloriesEvent.getCalories() + " kCal", textView);
            }

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setCalorieData(bandCaloriesEvent);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Calories");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Calories" + File.separator + "Calories_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(bandCaloriesEvent.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Calories" + File.separator + "Calories_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2) {
                                try {
                                    csvWriter.writeNext(new String[]{String.valueOf(bandCaloriesEvent.getTimestamp()),
                                            str, String.valueOf(bandCaloriesEvent.getCaloriesToday()),
                                            String.valueOf(bandCaloriesEvent.getCalories())});
                                } catch (Exception e) {
                                    SensorsFragment.appendToUI(e.toString(), textView);
                                }
                            } else {
                                csvWriter.writeNext(new String[]{String.valueOf(bandCaloriesEvent.getTimestamp()),
                                        str, String.valueOf(bandCaloriesEvent.getCalories())});
                            }
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Calories" + File.separator + "Calories_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2)
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.calories_today), MainActivity.sContext.getString(R.string.calories)});
                            else
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.calories)});
                            csvWriter.close();
                        }
                    } catch (IOException paramAnonymousBandCaloriesEvent) {
                        Log.e("CSV", paramAnonymousBandCaloriesEvent.toString());
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class ContactEventListener implements BandContactEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandContactChanged(final BandContactEvent bandContactEvent) {
        if (bandContactEvent != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (bandContactEvent.getContactState()) {
                            case UNKNOWN:
                                SensorActivity.chartAdapter.add(-1f);
                                break;
                            case NOT_WORN:
                                SensorActivity.chartAdapter.add(0f);
                                break;
                            case WORN:
                                SensorActivity.chartAdapter.add(2f);
                                break;
                        }
                    }
                });

            SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.contact_status) + " = " + bandContactEvent.getContactState(), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setContactData(bandContactEvent);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Contact");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Contact" + File.separator + "Contact_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(bandContactEvent.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Contact" + File.separator + "Contact_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(bandContactEvent.getTimestamp()), str,
                                    String.valueOf(bandContactEvent.getContactState())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Contact" + File.separator + "Contact_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.contact_status)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class DistanceEventListener implements BandDistanceEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandDistanceChanged(final BandDistanceEvent bandDistanceEvent) {
        if (bandDistanceEvent != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add(bandDistanceEvent.getPace());
                    }
                });

            if (MainActivity.band2) {
                try {
                    SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.motion_type) + " = " + bandDistanceEvent.getMotionType() +
                            "\n" + MainActivity.sContext.getString(R.string.pace) + " (ms/m) = " + bandDistanceEvent.getPace() +
                            "\n" + MainActivity.sContext.getString(R.string.speed) + " (cm/s) = " + bandDistanceEvent.getSpeed() +
                            "\n" + MainActivity.sContext.getString(R.string.distance_today) + " = " + bandDistanceEvent.getDistanceToday() / 100000L +
                            " km\n" + MainActivity.sContext.getString(R.string.total_distance) + " = " + bandDistanceEvent.getTotalDistance() / 100000L +
                            " km", textView);
                } catch (Exception e) {
                    SensorsFragment.appendToUI(e.toString(), textView);
                }
            } else {
                SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.motion_type) + " = " + bandDistanceEvent.getMotionType() +
                        "\n" + MainActivity.sContext.getString(R.string.pace) + " (ms/m) = " + bandDistanceEvent.getPace() +
                        "\n" + MainActivity.sContext.getString(R.string.speed) + " (cm/s) = " + bandDistanceEvent.getSpeed() +
                        "\n" + MainActivity.sContext.getString(R.string.total_distance) + " = " + bandDistanceEvent.getTotalDistance() / 100000L +
                        " km", textView);
            }

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setDistanceData(bandDistanceEvent);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Distance");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Distance" + File.separator + "Distance_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(bandDistanceEvent.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Distance" + File.separator + "Distance_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2) {
                                try {
                                    csvWriter.writeNext(new String[]{String.valueOf(bandDistanceEvent.getTimestamp()),
                                            str, String.valueOf(bandDistanceEvent.getMotionType()),
                                            String.valueOf(bandDistanceEvent.getPace()),
                                            String.valueOf(bandDistanceEvent.getSpeed()),
                                            String.valueOf(bandDistanceEvent.getDistanceToday()),
                                            String.valueOf(bandDistanceEvent.getTotalDistance())});
                                } catch (Exception e) {
                                    SensorsFragment.appendToUI(e.toString(), textView);
                                }
                            } else {
                                csvWriter.writeNext(new String[]{String.valueOf(bandDistanceEvent.getTimestamp()),
                                        str, String.valueOf(bandDistanceEvent.getMotionType()),
                                        String.valueOf(bandDistanceEvent.getPace()),
                                        String.valueOf(bandDistanceEvent.getSpeed()),
                                        String.valueOf(bandDistanceEvent.getTotalDistance())});
                            }
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Distance" + File.separator + "Distance_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2)
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.motion_type), MainActivity.sContext.getString(R.string.pace), MainActivity.sContext.getString(R.string.speed), MainActivity.sContext.getString(R.string.distance_today), MainActivity.sContext.getString(R.string.total_distance)});
                            else
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.motion_type), MainActivity.sContext.getString(R.string.pace), MainActivity.sContext.getString(R.string.speed), MainActivity.sContext.getString(R.string.total_distance)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class GsrEventListener implements BandGsrEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandGsrChanged(final BandGsrEvent event) {
        if (event != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add((float) event.getResistance());
                    }
                });

            SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.resistance)
                    + String.format(" = %d kOhms\n",
                    event.getResistance()), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setGsrData(event);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "GSR");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "GSR" + File.separator + "GSR_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "GSR" + File.separator + "GSR_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()),
                                    str, String.valueOf(event.getResistance())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "GSR" + File.separator + "GSR_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.resistance)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class GyroscopeEventListener implements BandGyroscopeEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandGyroscopeChanged(final BandGyroscopeEvent bandGyroscopeEvent) {
        if (bandGyroscopeEvent != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add(bandGyroscopeEvent.getAngularVelocityX());
                    }
                });

            SensorsFragment.appendToUI(String.format("X = %.3f (m/s²) \nY = %.3f (m/s²)\nZ = %.3f (m/s²)\n" +
                            "X = %.3f (°/sec)\nY = %.3f (°/sec)\nZ = %.3f (°/sec)",
                    bandGyroscopeEvent.getAccelerationX(),
                    bandGyroscopeEvent.getAccelerationY(),
                    bandGyroscopeEvent.getAccelerationZ(),
                    bandGyroscopeEvent.getAngularVelocityX(),
                    bandGyroscopeEvent.getAngularVelocityY(),
                    bandGyroscopeEvent.getAngularVelocityZ()),
                    textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setGyroscopeData(bandGyroscopeEvent);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Gyroscope");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Gyroscope" + File.separator + "Gyroscope_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(bandGyroscopeEvent.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Gyroscope" + File.separator + "Gyroscope_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(bandGyroscopeEvent.getTimestamp()),
                                    str, String.valueOf(bandGyroscopeEvent.getAccelerationX()),
                                    String.valueOf(bandGyroscopeEvent.getAccelerationY()),
                                    String.valueOf(bandGyroscopeEvent.getAccelerationZ()),
                                    String.valueOf(bandGyroscopeEvent.getAngularVelocityX()),
                                    String.valueOf(bandGyroscopeEvent.getAngularVelocityY()),
                                    String.valueOf(bandGyroscopeEvent.getAngularVelocityZ())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Gyroscope" + File.separator + "Gyroscope_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), "X m/s²", "Y", "Z", "X °/sec", "Y", "Z"});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class HeartRateEventListener implements BandHeartRateEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandHeartRateChanged(final BandHeartRateEvent event) {
        if (event != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add((float) event.getHeartRate());
                    }
                });

            SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.heart_rate) + String.format(" = %d ", event.getHeartRate())
                    + MainActivity.sContext.getString(R.string.beats_per_minute) + "\n" + MainActivity.sContext.getString(R.string.quality)
                    + String.format(" = %s", event.getQuality()), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setHeartRateData(event);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "HeartRate");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "HeartRate" + File.separator + "HeartRate_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "HeartRate" + File.separator + "HeartRate_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()),
                                    str, String.valueOf(event.getHeartRate()), String.valueOf(event.getQuality())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "HeartRate" + File.separator + "HeartRate_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.heart_rate), MainActivity.sContext.getString(R.string.quality)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class PedometerEventListener implements BandPedometerEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandPedometerChanged(final BandPedometerEvent bandPedometerEvent) {
        if (bandPedometerEvent != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add((float) bandPedometerEvent.getTotalSteps());
                    }
                });

            if (MainActivity.band2) {
                try {
                    SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.steps_today) + " = " + bandPedometerEvent.getStepsToday() + "\n" +
                            MainActivity.sContext.getString(R.string.total_steps) + " = " + bandPedometerEvent.getTotalSteps(), textView);
                } catch (Exception e) {
                    SensorsFragment.appendToUI(e.toString(), textView);
                }
            } else {
                SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.total_steps) + " = " + bandPedometerEvent.getTotalSteps(), textView);
            }

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setPedometerData(bandPedometerEvent);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Pedometer");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Pedometer" + File.separator + "Pedometer_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(bandPedometerEvent.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Pedometer" + File.separator + "Pedometer_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2) {
                                try {
                                    csvWriter.writeNext(new String[]{String.valueOf(bandPedometerEvent.getTimestamp()),
                                            str, String.valueOf(bandPedometerEvent.getStepsToday()), String.valueOf(bandPedometerEvent.getTotalSteps())});
                                } catch (Exception e) {
                                    SensorsFragment.appendToUI(e.toString(), textView);
                                }
                            } else {
                                csvWriter.writeNext(new String[]{String.valueOf(bandPedometerEvent.getTimestamp()),
                                        str, String.valueOf(bandPedometerEvent.getTotalSteps())});
                            }
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "Pedometer" + File.separator + "Pedometer_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2)
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.steps_today), MainActivity.sContext.getString(R.string.total_steps)});
                            else
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.total_steps)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class RRIntervalEventListener implements BandRRIntervalEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandRRIntervalChanged(final BandRRIntervalEvent event) {
        if (event != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add((float) event.getInterval());
                    }
                });

            SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.rr)
                    + String.format(" = %.3f s\n", event.getInterval()), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setRrIntervalData(event);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "RRInterval");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "RRInterval" + File.separator + "RRInterval_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(event.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "RRInterval" + File.separator + "RRInterval_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(event.getTimestamp()), str,
                                    String.valueOf(event.getInterval())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "RRInterval" + File.separator + "RRInterval_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.rr)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class SkinTemperatureEventListener implements BandSkinTemperatureEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandSkinTemperatureChanged(final BandSkinTemperatureEvent bandSkinTemperatureEvent) {
        if (bandSkinTemperatureEvent != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SensorActivity.chartAdapter.add(bandSkinTemperatureEvent.getTemperature());
                    }
                });

            SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.temperature)
                    + String.format(" = " + bandSkinTemperatureEvent.getTemperature() + " °C"
                    + " = %.2f F", 1.8 * bandSkinTemperatureEvent.getTemperature() + 32), textView);

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setSkinTemperatureData(bandSkinTemperatureEvent);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "SkinTemperature");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "SkinTemperature" + File.separator + "SkinTemperature_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(bandSkinTemperatureEvent.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "SkinTemperature" + File.separator + "SkinTemperature_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{String.valueOf(bandSkinTemperatureEvent.getTimestamp()),
                                    str, String.valueOf(bandSkinTemperatureEvent.getTemperature())});
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "SkinTemperature" + File.separator + "SkinTemperature_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.temperature)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class UVEventListener implements BandUVEventListener {

    private TextView textView;
    private boolean graph;

    public void setViews(TextView textView, boolean graph) {
        this.textView = textView;
        this.graph = graph;
    }

    @Override
    public void onBandUVChanged(final BandUVEvent bandUVEvent) {
        if (bandUVEvent != null) {
            if (graph)
                MainActivity.sActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (bandUVEvent.getUVIndexLevel()) {
                            case NONE:
                                SensorActivity.chartAdapter.add(0f);
                                break;
                            case LOW:
                                SensorActivity.chartAdapter.add(1f);
                                break;
                            case MEDIUM:
                                SensorActivity.chartAdapter.add(2f);
                                break;
                            case HIGH:
                                SensorActivity.chartAdapter.add(3f);
                                break;
                            case VERY_HIGH:
                                SensorActivity.chartAdapter.add(4f);
                                break;
                        }
                    }
                });

            if (MainActivity.band2) {
                try {
                    SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.uv_today) + " = " + bandUVEvent.getUVExposureToday() + "\n" +
                            MainActivity.sContext.getString(R.string.uv_index) + " = " + bandUVEvent.getUVIndexLevel(), textView);
                } catch (Exception e) {
                    SensorsFragment.appendToUI(e.toString(), textView);
                }
            } else {
                SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.uv_index) + " = " + bandUVEvent.getUVIndexLevel(), textView);
            }

            if (MainActivity.sharedPreferences.getBoolean("log", false)) {
                MainActivity.bandSensorData.setUvIndexData(bandUVEvent);

                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "UV");
                if (file.exists() || file.isDirectory()) {
                    try {
                        Date date = new Date();
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "UV" + File.separator + "UV_" + DateFormat.getDateInstance().format(date) + ".csv").exists()) {
                            String str = DateFormat.getDateTimeInstance().format(bandUVEvent.getTimestamp());
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "UV" + File.separator + "UV_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2) {
                                try {
                                    csvWriter.writeNext(new String[]{String.valueOf(bandUVEvent.getTimestamp()),
                                            str, String.valueOf(bandUVEvent.getUVExposureToday()), String.valueOf(bandUVEvent.getUVIndexLevel())});
                                } catch (Exception e) {
                                    SensorsFragment.appendToUI(e.toString(), textView);
                                }
                            } else {
                                csvWriter.writeNext(new String[]{String.valueOf(bandUVEvent.getTimestamp()),
                                        str, String.valueOf(bandUVEvent.getUVIndexLevel())});
                            }
                            csvWriter.close();
                        } else {
                            CSVWriter csvWriter = new CSVWriter(new FileWriter(path + File.separator + "CompanionForBand" + File.separator + "UV" + File.separator + "UV_" + DateFormat.getDateInstance().format(date) + ".csv", true));
                            if (MainActivity.band2)
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.uv_today), MainActivity.sContext.getString(R.string.uv_index)});
                            else
                                csvWriter.writeNext(new String[]{MainActivity.sContext.getString(R.string.timestamp), MainActivity.sContext.getString(R.string.date_time), MainActivity.sContext.getString(R.string.uv_index)});
                            csvWriter.close();
                        }
                    } catch (IOException e) {
                        //
                    }
                } else {
                    file.mkdirs();
                }
            }
        }
    }
} public class Band1SubscriptionTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            if (BandUtils.getConnectedBandClient()) {
                if (MainActivity.sharedPreferences.getBoolean("log", false))
                    MainActivity.client.getSensorManager().registerAccelerometerEventListener
                            (SensorsFragment.bandAllSensorsAccelerometerEventListener, SampleRate.MS128);

                if (MainActivity.sharedPreferences.getBoolean("Accelerometer", true)) {
                    switch (MainActivity.sharedPreferences.getInt("acc_hz", 13)) {
                        case 11:
                            MainActivity.client.getSensorManager().registerAccelerometerEventListener(
                                    SensorsFragment.bandAccelerometerEventListener, SampleRate.MS16);
                            break;
                        case 12:
                            MainActivity.client.getSensorManager().registerAccelerometerEventListener(
                                    SensorsFragment.bandAccelerometerEventListener, SampleRate.MS32);
                            break;
                        default:
                            MainActivity.client.getSensorManager().registerAccelerometerEventListener(
                                    SensorsFragment.bandAccelerometerEventListener, SampleRate.MS128);
                    }
                }

                if (MainActivity.sharedPreferences.getBoolean("Gyroscope", true)) {
                    switch (MainActivity.sharedPreferences.getInt("gyr_hz", 23)) {
                        case 21:
                            MainActivity.client.getSensorManager().registerGyroscopeEventListener(
                                    SensorsFragment.bandGyroscopeEventListener, SampleRate.MS16);
                            break;
                        case 22:
                            MainActivity.client.getSensorManager().registerGyroscopeEventListener(
                                    SensorsFragment.bandGyroscopeEventListener, SampleRate.MS32);
                            break;
                        default:
                            MainActivity.client.getSensorManager().registerGyroscopeEventListener(
                                    SensorsFragment.bandGyroscopeEventListener, SampleRate.MS128);
                    }
                }

                if (MainActivity.sharedPreferences.getBoolean("Calories", true))
                    MainActivity.client.getSensorManager().registerCaloriesEventListener(SensorsFragment.bandCaloriesEventListener);
                if (MainActivity.sharedPreferences.getBoolean("Contact", true))
                    MainActivity.client.getSensorManager().registerContactEventListener(SensorsFragment.bandContactEventListener);
                if (MainActivity.sharedPreferences.getBoolean("Distance", true))
                    MainActivity.client.getSensorManager().registerDistanceEventListener(SensorsFragment.bandDistanceEventListener);
                if (MainActivity.sharedPreferences.getBoolean("Pedometer", true))
                    MainActivity.client.getSensorManager().registerPedometerEventListener(SensorsFragment.bandPedometerEventListener);
                if (MainActivity.sharedPreferences.getBoolean("Skin Temperature", true))
                    MainActivity.client.getSensorManager().registerSkinTemperatureEventListener(SensorsFragment.bandSkinTemperatureEventListener);
                if (MainActivity.sharedPreferences.getBoolean("UV", true))
                    MainActivity.client.getSensorManager().registerUVEventListener(SensorsFragment.bandUVEventListener);
            } else {
                MainActivity.appendToUI(MainActivity.sContext.getString(R.string.band_not_found), "Style.ALERT");
            }
        } catch (BandException e) {
            BandUtils.handleBandException(e);
        } catch (Exception e) {
            MainActivity.appendToUI(e.getMessage(), "Style.ALERT");
        }
        return null;
    }
} public class Band2SubscriptionTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            if (BandUtils.getConnectedBandClient()) {
                if (MainActivity.band2) {
                    if (MainActivity.sharedPreferences.getBoolean("Altimeter", true))
                        MainActivity.client.getSensorManager().registerAltimeterEventListener(SensorsFragment.bandAltimeterEventListener);
                    if (MainActivity.sharedPreferences.getBoolean("Ambient Light", true))
                        MainActivity.client.getSensorManager().registerAmbientLightEventListener(SensorsFragment.bandAmbientLightEventListener);
                    if (MainActivity.sharedPreferences.getBoolean("Barometer", true))
                        MainActivity.client.getSensorManager().registerBarometerEventListener(SensorsFragment.bandBarometerEventListener);

                    if (MainActivity.sharedPreferences.getBoolean("GSR", true))
                        if (MainActivity.sharedPreferences.getInt("gsr_hz", 31) == 31)
                            MainActivity.client.getSensorManager().registerGsrEventListener(SensorsFragment.bandGsrEventListener, GsrSampleRate.MS200);
                        else
                            MainActivity.client.getSensorManager().registerGsrEventListener(SensorsFragment.bandGsrEventListener, GsrSampleRate.MS5000);

                    SensorsFragment.appendToUI("Firmware Version : " + MainActivity.client.getFirmwareVersion().await()
                            + "\nHardware Version : " + MainActivity.client.getHardwareVersion().await(), SensorsFragment.band2TV);
                } else {
                    SensorsFragment.appendToUI("Firmware Version : " + MainActivity.client.getFirmwareVersion().await()
                            + "\nHardware Version : " + MainActivity.client.getHardwareVersion().await()
                            + "\n\n" + MainActivity.sContext.getString(R.string.band_2_required), SensorsFragment.band2TV);
                }
            } else {
                MainActivity.appendToUI(MainActivity.sContext.getString(R.string.band_not_found), "Style.ALERT");
            }
        } catch (BandException e) {
            BandUtils.handleBandException(e);
        } catch (Exception e) {
            MainActivity.appendToUI(e.getMessage(), "Style.ALERT");
        }
        return null;
    }
} public class HeartRateSubscriptionTask extends AsyncTask<TextView, Void, Void> {
    @Override
    protected Void doInBackground(TextView... params) {
        try {
            if (BandUtils.getConnectedBandClient()) {
                if (MainActivity.sharedPreferences.getBoolean("Heart Rate", true))
                    if (MainActivity.client.getSensorManager().getCurrentHeartRateConsent() == UserConsent.GRANTED) {
                        MainActivity.client.getSensorManager().registerHeartRateEventListener(SensorsFragment.bandHeartRateEventListener);
                    } else {
                        MainActivity.sActivity.runOnUiThread(new Runnable() {
                            @SuppressWarnings("unchecked")
                            @Override
                            public void run() {
                                new HeartRateConsentTask().execute(SensorsFragment.reference);
                            }
                        });
                        SensorsFragment.appendToUI(MainActivity.sContext.getString(R.string.heart_rate_consent) + "\n", params[0]);
                    }
            } else {
                MainActivity.appendToUI(MainActivity.sContext.getString(R.string.band_not_found), "Style.ALERT");
            }
        } catch (BandException e) {
            BandUtils.handleBandException(e);
        } catch (Exception e) {
            MainActivity.appendToUI(e.getMessage(), "Style.ALERT");
        }
        return null;
    }
} public class RRIntervalSubscriptionTask extends AsyncTask<TextView, Void, Void> {
    @Override
    protected Void doInBackground(TextView... params) {
        try {
            if (BandUtils.getConnectedBandClient()) {
                if (MainActivity.band2) {
                    if (MainActivity.sharedPreferences.getBoolean("RR Interval", true))
                        if (MainActivity.client.getSensorManager().getCurrentHeartRateConsent()
                                == UserConsent.GRANTED) {
                            MainActivity.client.getSensorManager()
                                    .registerRRIntervalEventListener(SensorsFragment.bandRRIntervalEventListener);
                        } else {
                            SensorsFragment.appendToUI(MainActivity.sContext
                                            .getString(R.string.heart_rate_consent) + "\n",
                                    params[0]);
                        }
                }
            } else {
                MainActivity.appendToUI(MainActivity.sContext.getString(R.string.band_not_found),
                        "Style.ALERT");
            }
        } catch (BandException e) {
            BandUtils.handleBandException(e);
        } catch (Exception e) {
            MainActivity.appendToUI(e.getMessage(), "Style.ALERT");
        }
        return null;
    }
}
import android.Manifest;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import com.microsoft.band.sensors.BandAccelerometerEventListener;
import com.microsoft.band.sensors.BandAltimeterEventListener;
import com.microsoft.band.sensors.BandAmbientLightEventListener;
import com.microsoft.band.sensors.BandBarometerEventListener;
import com.microsoft.band.sensors.BandCaloriesEventListener;
import com.microsoft.band.sensors.BandContactEventListener;
import com.microsoft.band.sensors.BandDistanceEventListener;
import com.microsoft.band.sensors.BandGsrEventListener;
import com.microsoft.band.sensors.BandGyroscopeEventListener;
import com.microsoft.band.sensors.BandHeartRateEventListener;
import com.microsoft.band.sensors.BandPedometerEventListener;
import com.microsoft.band.sensors.BandRRIntervalEventListener;
import com.microsoft.band.sensors.BandSkinTemperatureEventListener;
import com.microsoft.band.sensors.BandUVEventListener;
import com.pimp.companionforband.R;
import com.pimp.companionforband.activities.main.MainActivity;
import com.pimp.companionforband.utils.band.listeners.AccelerometerEventListener;
import com.pimp.companionforband.utils.band.listeners.AllSensorsAccelerometerEventListener;
import com.pimp.companionforband.utils.band.listeners.AltimeterEventListener;
import com.pimp.companionforband.utils.band.listeners.AmbientLightEventListener;
import com.pimp.companionforband.utils.band.listeners.BarometerEventListener;
import com.pimp.companionforband.utils.band.listeners.CaloriesEventListener;
import com.pimp.companionforband.utils.band.listeners.ContactEventListener;
import com.pimp.companionforband.utils.band.listeners.DistanceEventListener;
import com.pimp.companionforband.utils.band.listeners.GsrEventListener;
import com.pimp.companionforband.utils.band.listeners.GyroscopeEventListener;
import com.pimp.companionforband.utils.band.listeners.HeartRateEventListener;
import com.pimp.companionforband.utils.band.listeners.PedometerEventListener;
import com.pimp.companionforband.utils.band.listeners.RRIntervalEventListener;
import com.pimp.companionforband.utils.band.listeners.SkinTemperatureEventListener;
import com.pimp.companionforband.utils.band.listeners.UVEventListener;
import com.pimp.companionforband.utils.band.subscription.Band1SubscriptionTask;
import com.pimp.companionforband.utils.band.subscription.Band2SubscriptionTask;
import com.pimp.companionforband.utils.band.subscription.HeartRateSubscriptionTask;
import com.pimp.companionforband.utils.band.subscription.RRIntervalSubscriptionTask;
import java.lang.ref.WeakReference;
/*
 * Companion for Band
 * Copyright (C) 2016  Adithya J
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

package com.pimp.companionforband.fragments.sensors;




public class SensorsFragment extends Fragment {

    public static WeakReference<Activity> reference;
    public static TextView band2TV, logTV;
    public static CardView accelerometerCard, altimeterCard, ambientLightCard, barometerCard,
            caloriesCard, contactCard, distanceCard, gsrCard, gyroscopeCard, heartRateCard,
            pedometerCard, rrIntervalCard, skinTemperatureCard, uvCard;

    public static BandAccelerometerEventListener bandAllSensorsAccelerometerEventListener;
    public static BandAccelerometerEventListener bandAccelerometerEventListener;
    public static BandAltimeterEventListener bandAltimeterEventListener;
    public static BandAmbientLightEventListener bandAmbientLightEventListener;
    public static BandBarometerEventListener bandBarometerEventListener;
    public static BandCaloriesEventListener bandCaloriesEventListener;
    public static BandContactEventListener bandContactEventListener;
    public static BandDistanceEventListener bandDistanceEventListener;
    public static BandGsrEventListener bandGsrEventListener;
    public static BandGyroscopeEventListener bandGyroscopeEventListener;
    public static BandHeartRateEventListener bandHeartRateEventListener;
    public static BandPedometerEventListener bandPedometerEventListener;
    public static BandRRIntervalEventListener bandRRIntervalEventListener;
    public static BandSkinTemperatureEventListener bandSkinTemperatureEventListener;
    public static BandUVEventListener bandUVEventListener;
    View.OnClickListener cardViewOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView sensorName = (TextView) v.findViewById(R.id.txtName);
            Intent intent = new Intent(getContext(), SensorActivity.class);
            intent.putExtra("sensor_name", sensorName.getText().toString());

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                String transitionName = getResources().getString(R.string.transition_sensor_name);

                ActivityOptions transitionActivityOptions = ActivityOptions
                        .makeSceneTransitionAnimation(getActivity(), sensorName, transitionName);
                startActivity(intent, transitionActivityOptions.toBundle());
            } else {
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.fade_back);
            }
        }
    };

    public static void appendToUI(final String string, final TextView textView) {
        try {
            MainActivity.sActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(string);
                }
            });
        } catch (Exception e) {
            //
        }
    }

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

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        reference = new WeakReference<Activity>(getActivity());
        band2TV = (TextView) view.findViewById(R.id.band2TxtStatus);
        accelerometerCard = (CardView) view.findViewById(R.id.accelerometer_card);
        altimeterCard = (CardView) view.findViewById(R.id.altimeter_card);
        ambientLightCard = (CardView) view.findViewById(R.id.ambientLight_card);
        barometerCard = (CardView) view.findViewById(R.id.barometer_card);
        caloriesCard = (CardView) view.findViewById(R.id.calories_card);
        contactCard = (CardView) view.findViewById(R.id.contact_card);
        distanceCard = (CardView) view.findViewById(R.id.distance_card);
        gsrCard = (CardView) view.findViewById(R.id.gsr_card);
        gyroscopeCard = (CardView) view.findViewById(R.id.gyroscope_card);
        heartRateCard = (CardView) view.findViewById(R.id.heartRate_card);
        pedometerCard = (CardView) view.findViewById(R.id.pedometer_card);
        rrIntervalCard = (CardView) view.findViewById(R.id.rrInterval_card);
        skinTemperatureCard = (CardView) view.findViewById(R.id.skinTemperature_card);
        uvCard = (CardView) view.findViewById(R.id.uv_card);

        CardView[] cardViews = {accelerometerCard, altimeterCard, ambientLightCard, barometerCard,
                caloriesCard, contactCard, distanceCard, gsrCard, gyroscopeCard, heartRateCard,
                pedometerCard, rrIntervalCard, skinTemperatureCard, uvCard};
        String[] sensors = {"Accelerometer", "Altimeter", "Ambient Light", "Barometer", "Calories",
                "Contact", "Distance", "GSR", "Gyroscope", "Heart Rate", "Pedometer", "RR Interval",
                "Skin Temperature", "UV"};

        bandAllSensorsAccelerometerEventListener = new AllSensorsAccelerometerEventListener();
        bandAccelerometerEventListener = new AccelerometerEventListener();
        bandAltimeterEventListener = new AltimeterEventListener();
        bandAmbientLightEventListener = new AmbientLightEventListener();
        bandBarometerEventListener = new BarometerEventListener();
        bandCaloriesEventListener = new CaloriesEventListener();
        bandContactEventListener = new ContactEventListener();
        bandDistanceEventListener = new DistanceEventListener();
        bandGsrEventListener = new GsrEventListener();
        bandGyroscopeEventListener = new GyroscopeEventListener();
        bandHeartRateEventListener = new HeartRateEventListener();
        bandPedometerEventListener = new PedometerEventListener();
        bandRRIntervalEventListener = new RRIntervalEventListener();