/**
   * Called whenever this activity is called from within the application, like from the login
   * dialog.
   */
  @SuppressLint("NewApi")
  @Override
  public void onResume() {
    super.onResume();

    // We are going to do a series of tasks depending on whether or not we have connectivity
    // if we have connectivity: user can change ProjectNumber, set it originally to the user's last
    // choice, and automatically login
    if (api.hasConnectivity()) {
      // Give the boolean canChangeProjectNum a value of either true or false depending on whether
      // or not we are connected to the Internet
      canChangeProjectNum = true;
      if (android.os.Build.VERSION.SDK_INT >= 11) invalidateOptionsMenu();
      setProjectIdtoUsersChoice();
      AutoLogin();
      // projectID = projectId;
      // loginNow = false;
    } else {
      // TODO UNComment
      canChangeProjectNum = false;
      if (android.os.Build.VERSION.SDK_INT >= 11) invalidateOptionsMenu();
      // loginNow = true;
      setProjectIdEmpty();
    }

    // Get the last know recording interval
    mInterval =
        Integer.parseInt(
            getSharedPreferences(INTERVAL_PREFS_KEY, Context.MODE_PRIVATE)
                .getString(INTERVAL_VALUE_KEY, DEFAULT_INTERVAL + ""));

    // Rebuild the upload queue
    if (uq != null) uq.buildQueueFromFile();

    // Check to see if the recording was canceled while running
    if (running) {
      Intent i = new Intent(DataWalk.this, ForceStop.class);
      startActivityForResult(i, DIALOG_FORCE_STOP);
    }

    // Restart the GPS counter
    if (mLocationManager != null) initLocationManager();
    if (gpsTimer == null) waitingForGPS();

    // Update the text in the text boxes on the main UI
    if (projectID == "-1") {
      expNumBox.setText(
          "Project number cannot be choose until you are connected to the intenet." + projectID);
    } else {
      expNumBox.setText("Project Number: " + projectID);
    }
    if (mInterval == 1000) {
      rateBox.setText("Data Recorded Every: 1 second");
    } else if (mInterval == 60000) {
      rateBox.setText("Data Recorded Every: 1 Minute");
    } else {
      rateBox.setText("Data Recorded Every: " + mInterval / 1000 + " seconds");
    }
  } // ends onResume
  @Override
  public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);
    dontPromptMeTwice = false;

    if (reqCode == EXPERIMENT_REQUESTED) {
      if (resultCode == RESULT_OK) {
        SharedPreferences prefs = getSharedPreferences("PROJID", 0);
        experimentNumber = prefs.getString("project_id", null);
        if (experimentNumber == null) {
          if (useDev) {
            experimentNumber = DEFAULT_PROJ_DEV;
          } else {
            experimentNumber = DEFAULT_PROJ_PROD;
          }
        }
        dfm = new DataFieldManager(Integer.parseInt(experimentNumber), api, mContext, f);
        dfm.getOrder();
      }
    } else if (reqCode == QUEUE_UPLOAD_REQUESTED) {
      uq.buildQueueFromFile();

    } else if (reqCode == UPLOAD_OK_REQUESTED) {
      if (resultCode == RESULT_OK) {
        if (len == 0 || len2 == 0) {
          w.make("There are no data to upload!", Waffle.LENGTH_LONG, Waffle.IMAGE_X);
          OrientationManager.enableRotation(CarRampPhysicsV2.this);
        } else new UploadTask().execute();
      } else {
        w.make("Data set discarded", Waffle.LENGTH_LONG, Waffle.IMAGE_WARN);
        OrientationManager.enableRotation(CarRampPhysicsV2.this);
      }
    } else if (reqCode == LOGIN_STATUS_REQUESTED) {
      if (resultCode == RESULT_OK) {
        if (loggedInAs == null) loggedInAs = (TextView) findViewById(R.id.loginStatus);
        loggedInAs.setText(
            getResources().getString(R.string.logged_in_as)
                + " "
                + data.getStringExtra("username")
                + ", Name: "
                + firstName
                + " "
                + lastInitial);
        dfm = new DataFieldManager(Integer.parseInt(experimentNumber), api, mContext, f);
        dfm.getOrder();
      }
    } else if (reqCode == RECORDING_LENGTH_REQUESTED) {
      if (resultCode == RESULT_OK) {
        length = Integer.parseInt(data.getStringExtra("input"));
        countdown = length;
        SharedPreferences prefs = getSharedPreferences("RECORD_LENGTH", 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("length", length);
        // Below is a math fail
        //				if (length <= 25) {
        //					INTERVAL = 50;
        //				} else {
        //					INTERVAL = 2 * length;
        //				}
        editor.putInt("Interval", INTERVAL);
        editor.commit();
      }
    } else if (reqCode == resultGotName) {
      if (resultCode == RESULT_OK) {
        final SharedPreferences mPrefs =
            new ObscuredSharedPreferences(
                CarRampPhysicsV2.mContext,
                CarRampPhysicsV2.mContext.getSharedPreferences("USER_INFO", Context.MODE_PRIVATE));
        if (!inApp) inApp = true;
        loggedInAs.setText(
            getResources().getString(R.string.logged_in_as)
                + " "
                + mPrefs.getString("username", "")
                + ", Name: "
                + firstName
                + " "
                + lastInitial);
      } else {
        if (!inApp) finish();
      }
    } else if (reqCode == RESET_REQUESTED) {
      if (resultCode == RESULT_OK) {
        SharedPreferences prefs = getSharedPreferences("RECORD_LENGTH", 0);
        countdown = length = prefs.getInt("length", 10);
        final SharedPreferences mPrefs =
            new ObscuredSharedPreferences(
                CarRampPhysicsV2.mContext,
                CarRampPhysicsV2.mContext.getSharedPreferences("USER_INFO", Context.MODE_PRIVATE));
        SharedPreferences.Editor mOSPEdit = mPrefs.edit();
        mOSPEdit.putString("username", DEFAULT_USER).commit();
        mOSPEdit.putString("password", DEFAULT_USER).commit();

        new OnCreateLoginTask().execute();
        loggedInAs.setText(
            getResources().getString(R.string.logged_in_as)
                + " "
                + mPrefs.getString("username", "")
                + ", Name: "
                + firstName
                + " "
                + lastInitial);

        SharedPreferences eprefs = getSharedPreferences("PROJID", 0);
        SharedPreferences.Editor editor = eprefs.edit();
        if (useDev) {
          experimentNumber = DEFAULT_PROJ_DEV;
        } else {
          experimentNumber = DEFAULT_PROJ_PROD;
        }
        editor.putString("project_id", experimentNumber);
        editor.commit();
        INTERVAL = 50;

        SharedPreferences rprefs = getSharedPreferences("RECORD_SETTINGS", 0);
        SharedPreferences.Editor mEdit = rprefs.edit();
        mEdit.putBoolean("X", false);
        mEdit.putBoolean("Y", true);
        mEdit.putBoolean("Z", false);
        mEdit.putBoolean("Magnitude", false);
        mEdit.commit();

        x = z = mag = false;
        y = true;
        values.setText("Y: " + accel[1]);
        Log.d("fantastag", "resetti");
      }
    } else if (reqCode == SAVE_MODE_REQUESTED) {
      if (resultCode == RESULT_OK) {
        saveMode = true;
        CarRampPhysicsV2.experimentNumber = "-1";
        dfm = new DataFieldManager(Integer.parseInt(experimentNumber), api, mContext, f);
        dfm.getOrder();
      } else {
        if (!api.hasConnectivity()) {
          startActivityForResult(new Intent(mContext, SaveModeDialog.class), SAVE_MODE_REQUESTED);
        } else {
          saveMode = false;
        }
      }
    }
  }
  @Override
  public void onResume() {
    super.onResume();
    inPausedState = false;
    SharedPreferences prefs = getSharedPreferences(RecordSettings.RECORD_SETTINGS, 0);

    x = prefs.getBoolean("X", false);
    y = prefs.getBoolean("Y", true);
    z = prefs.getBoolean("Z", false);
    mag = prefs.getBoolean("Magnitude", false);

    String dataLabel = "";

    if (x) {
      dataLabel += "X: ";
    }
    if (y) {
      if (x) {
        dataLabel += " , Y: ";
      } else dataLabel += "Y: ";
    }
    if (z) {
      if (x || y) {
        dataLabel += " , Z: ";
      } else dataLabel += "Z: ";
    }

    if (mag) {
      if (x || y || z) {
        dataLabel += " , Magnitude: ";
      } else dataLabel += "Magnitude: ";
    }

    values.setText(dataLabel);

    if (usedHomeButton && running) {
      setupDone = false;
      timeHasElapsed = false;
      useMenu = true;
      countdown = length;

      running = false;
      startStop.setText("Hold to Start");
      startStop.setEnabled(true);
      startStop.setBackgroundResource(R.drawable.button_rsense);

      timeTimer.cancel();
      choiceViaMenu = false;
      startStop.setEnabled(true);
      dataSet = new JSONArray();
      OrientationManager.enableRotation(CarRampPhysicsV2.this);

      w.make("Data recording halted.", Waffle.LENGTH_SHORT, Waffle.IMAGE_X);
    }

    if (uq != null) uq.buildQueueFromFile();

    if (api.hasConnectivity() && saveMode) {
      SharedPreferences prefs2 = getSharedPreferences("PROJID", 0);
      experimentNumber = prefs2.getString("project_id", null);
      if (experimentNumber == null) {
        if (useDev) {
          experimentNumber = DEFAULT_PROJ_DEV;
        } else {
          experimentNumber = DEFAULT_PROJ_PROD;
        }
      }
      dfm = new DataFieldManager(Integer.parseInt(experimentNumber), api, mContext, f);
      dfm.getOrder();

      saveMode = false;
      System.out.println("Switching off save mode");
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    saved = savedInstanceState;
    mContext = this;

    api = API.getInstance(mContext);
    api.useDev(useDev);
    if (useDev) {
      baseSessionUrl = VIS_URL_DEV;
    } else {
      baseSessionUrl = VIS_URL_PROD;
    }

    f = new Fields();
    uq = new UploadQueue("carrampphysics", mContext, api);
    uq.buildQueueFromFile();

    w = new Waffle(mContext);

    // Save the default login info
    final SharedPreferences mPrefs =
        new ObscuredSharedPreferences(
            CarRampPhysicsV2.mContext,
            CarRampPhysicsV2.mContext.getSharedPreferences("USER_INFO", Context.MODE_PRIVATE));
    if (mPrefs.getString("username", "").equals("")) {
      SharedPreferences.Editor mEdit = mPrefs.edit();
      mEdit.putString("username", DEFAULT_USER).commit();
      mEdit.putString("password", DEFAULT_USER).commit();
    }

    dateString = "";

    mHandler = new Handler();

    startStop = (Button) findViewById(R.id.startStop);

    values = (TextView) findViewById(R.id.values);

    SharedPreferences prefs = getSharedPreferences("RECORD_LENGTH", 0);
    length = countdown = prefs.getInt("length", 10);

    new OnCreateLoginTask().execute();

    loggedInAs = (TextView) findViewById(R.id.loginStatus);
    loggedInAs.setText(
        getResources().getString(R.string.logged_in_as)
            + " "
            + mPrefs.getString("username", "")
            + ", Name: "
            + firstName
            + " "
            + lastInitial);
    SharedPreferences prefs2 = getSharedPreferences("PROJID", 0);
    experimentNumber = prefs2.getString("project_id", null);
    if (experimentNumber == null) {
      if (useDev) {
        experimentNumber = DEFAULT_PROJ_DEV;
      } else {
        experimentNumber = DEFAULT_PROJ_PROD;
      }
    }
    dfm = new DataFieldManager(Integer.parseInt(experimentNumber), api, mContext, f);
    dfm.getOrder();

    startStop.setOnLongClickListener(
        new OnLongClickListener() {

          @Override
          public boolean onLongClick(View arg0) {

            mMediaPlayer.setLooping(false);
            mMediaPlayer.start();

            if (!api.hasConnectivity() && !saveMode) {
              startActivityForResult(
                  new Intent(mContext, SaveModeDialog.class), SAVE_MODE_REQUESTED);
              return false;
            }

            if (running) {

              if (timeHasElapsed) {

                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

                setupDone = false;
                timeHasElapsed = false;
                useMenu = true;
                countdown = length;

                running = false;
                startStop.setText("Hold to Start");

                timeTimer.cancel();
                choiceViaMenu = false;

                startStop.setEnabled(true);
                startStop.setBackgroundResource(R.drawable.button_rsense);

                Intent dataIntent = new Intent(mContext, DataActivity.class);
                startActivityForResult(dataIntent, UPLOAD_OK_REQUESTED);

              } else if (usedHomeButton) {
                setupDone = false;
                timeHasElapsed = false;
                useMenu = true;
                countdown = length;

                running = false;
                startStop.setText("Hold to Start");

                timeTimer.cancel();
                choiceViaMenu = false;

                startStop.setEnabled(true);
                startStop.setBackgroundResource(R.drawable.button_rsense);
              }

            } else {

              OrientationManager.disableRotation(CarRampPhysicsV2.this);
              getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

              startStop.setEnabled(false);
              startStop.setBackgroundResource(R.drawable.button_rsense_green);

              dataSet = new JSONArray();
              elapsedMillis = 0;
              len = 0;
              len2 = 0;
              i = 0;
              currentTime = getUploadTime(0);

              SharedPreferences prefs = getSharedPreferences(RecordSettings.RECORD_SETTINGS, 0);

              x = prefs.getBoolean("X", false);
              y = prefs.getBoolean("Y", true);
              z = prefs.getBoolean("Z", false);
              mag = prefs.getBoolean("Magnitude", false);

              setEnabledFields();

              if (saveMode) {
                dfm.getOrder();
                System.out.println("Honk frogs@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
              }

              try {
                Thread.sleep(100);
              } catch (InterruptedException e) {
                w.make(
                    "Data recording has offset 100 milliseconds due to an error.",
                    Waffle.LENGTH_SHORT);
                e.printStackTrace();
              }

              useMenu = true;

              if (mSensorManager != null) {
                mSensorManager.registerListener(
                    CarRampPhysicsV2.this,
                    mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_FASTEST);
              }

              running = true;
              startStop.setText("" + countdown);

              timeTimer = new Timer();
              timeTimer.scheduleAtFixedRate(
                  new TimerTask() {

                    public void run() {

                      elapsedMillis += INTERVAL;

                      if (i >= (length * (1000 / INTERVAL))) {

                        timeTimer.cancel();
                        timeHasElapsed = true;

                        mHandler.post(
                            new Runnable() {
                              @Override
                              public void run() {
                                startStop.performLongClick();
                              }
                            });

                      } else {

                        i++;
                        len++;
                        len2++;

                        if (i % (1000 / INTERVAL) == 0) {
                          mHandler.post(
                              new Runnable() {
                                @Override
                                public void run() {
                                  startStop.setText("" + countdown);
                                }
                              });
                          countdown--;
                        }

                        f.timeMillis = currentTime + elapsedMillis;
                        Log.d("fantastag", "time added");

                        if (x) {
                          f.accel_x = toThou.format(accel[0]);
                          Log.d("fantastag", "X added");
                        }
                        if (y) {
                          f.accel_y = toThou.format(accel[1]);
                          Log.d("fantastag", "Y added");
                        }
                        if (z) {
                          f.accel_z = toThou.format(accel[2]);
                          Log.d("fantastag", "Z added");
                        }
                        if (mag) {
                          f.accel_total = toThou.format(accel[3]);
                          Log.d("fantastag", "Magnitude added");
                        }

                        if (!saveMode) {
                          dataSet.put(dfm.putData());
                          Log.d("tag", "NULLFROG");
                        } else {
                          dataSet.put(dfm.putDataForNoProjectID());
                          Log.d("tag", "NULLTOAD");
                        }
                      }
                    }
                  },
                  0,
                  INTERVAL);
            }

            return running;
          }
        });

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    if (mSensorManager != null) {
      mSensorManager.registerListener(
          CarRampPhysicsV2.this,
          mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
          SensorManager.SENSOR_DELAY_FASTEST);
      mSensorManager.registerListener(
          CarRampPhysicsV2.this,
          mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
          SensorManager.SENSOR_DELAY_FASTEST);
    }

    Criteria c = new Criteria();
    c.setAccuracy(Criteria.ACCURACY_FINE);

    accel = new float[4];
    orientation = new float[3];
    rawAccel = new float[3];
    rawMag = new float[3];

    mMediaPlayer = MediaPlayer.create(this, R.raw.beep);

    if (savedInstanceState == null) {
      if (firstName.equals("") || lastInitial.equals("")) {
        if (!dontPromptMeTwice) {
          startActivityForResult(new Intent(mContext, EnterNameActivity.class), resultGotName);
        }
      }
    }

    if (!api.hasConnectivity() && !saveMode) {
      startActivityForResult(new Intent(mContext, SaveModeDialog.class), SAVE_MODE_REQUESTED);
    }
  }
  /** Catches the returns from other activities back to DataWalk.java. */
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // If the user hits yes, launch a web page to view their data on iSENSE,
    // else do nothing.
    if (requestCode == DIALOG_VIEW_DATA) {

      if (resultCode == RESULT_OK) {
        projectURL += dataSetID + "?embed=true";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(projectURL));
        startActivity(i);
      }

      // If a new project has been selected, check to see if it is
      // actually valid.
    } else if (requestCode == PROJECT_REQUESTED) {

      if (api.hasConnectivity()) {
        if (resultCode == RESULT_OK) {
          setProjectIdtoUsersChoice();

          if (api.hasConnectivity()) {
            new GetProjectTask().execute();
          }
        } else if (resultCode == RESULT_CANCELED) {
          // This is called when they hit cancel.
          // In this situation, we want the UI to display the last project number the user entered.
          projectID = DEFAULT_PROJECT;
          // Set the project ID in preferences back to its default value
          SharedPreferences prefs = getSharedPreferences(Setup.PREFS_ID, Context.MODE_PRIVATE);
          SharedPreferences.Editor mEdit = prefs.edit();
          mEdit.putString(Setup.PROJECT_ID, DEFAULT_PROJECT);
          mEdit.commit();
        }
      } else {
        // There is no Internet so menu is disabled, thus the user will never reach this point.

      }

      // If the user hit yes, bring them to GPS settings.
    } else if (requestCode == DIALOG_NO_GPS) {
      if (resultCode == RESULT_OK) {
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
      }

      // The user left the app while it was running, so press the main
      // button to stop recording.
    } else if (requestCode == DIALOG_FORCE_STOP) {
      if (resultCode == RESULT_OK) {
        startStop.performLongClick();
      }

      // If the user uploaded data, offer to show the data on iSENSE
    } else if (requestCode == QUEUE_UPLOAD_REQUESTED) {
      uq.buildQueueFromFile();
      if (resultCode == RESULT_OK) {
        if (data != null) {
          dataSetID = data.getIntExtra(QueueLayout.LAST_UPLOADED_DATA_SET_ID, -1);
          if (dataSetID != -1) {
            Intent i = new Intent(DataWalk.this, ViewData.class);
            startActivityForResult(i, DIALOG_VIEW_DATA);
          }
        }
      }

      // Return of EnterNameActivity
    } else if (requestCode == NAME_REQUESTED) {

      // the user entered a valid name so update the main UI
      if (resultCode == RESULT_OK) {
        nameTxtBox.setText("Name: " + firstName + " " + lastInitial);
      } else {
        // Calls the enter name activity if a name has not yet been
        // entered.
        if (firstName.equals("") || lastInitial.equals("")) {
          startActivityForResult(new Intent(mContext, EnterNameActivity.class), NAME_REQUESTED);
          w.make(
              "You must enter your name before starting to record data.",
              Waffle.LENGTH_SHORT,
              Waffle.IMAGE_X);
        }
      }

      // Resets iSENSE and recording variables to their defaults.
    } else if (requestCode == RESET_REQUESTED) {

      if (resultCode == RESULT_OK) {

        // Set variables to default
        mInterval = DEFAULT_INTERVAL;
        loginName = DEFAULT_USERNAME;
        loginPass = DEFAULT_PASSWORD;
        firstName = "";
        lastInitial = "";
        projectID = DEFAULT_PROJECT;

        // Set the project ID in preferences back to its default value
        SharedPreferences prefs = getSharedPreferences(Setup.PREFS_ID, Context.MODE_PRIVATE);
        SharedPreferences.Editor mEdit = prefs.edit();
        mEdit.putString(Setup.PROJECT_ID, DEFAULT_PROJECT);
        mEdit.commit();

        // Set the default username and password in preferences back to
        // their default value
        final SharedPreferences mPrefs =
            new ObscuredSharedPreferences(
                DataWalk.mContext,
                DataWalk.mContext.getSharedPreferences(USER_PREFS_KEY, Context.MODE_PRIVATE));
        SharedPreferences.Editor mEditor = mPrefs.edit();
        mEditor.putString(DataWalk.USERNAME_KEY, loginName);
        mEditor.putString(DataWalk.PASSWORD_KEY, loginPass);
        mEditor.commit();

        // Tell the user his settings are back to default
        w.make("Settings have been reset to default.", Waffle.LENGTH_SHORT);

        // Launch the EnterNameActivity
        startActivityForResult(new Intent(mContext, EnterNameActivity.class), NAME_REQUESTED);
      }

      // Catches return from LoginIsense.java
    } else if (requestCode == LOGIN_ISENSE_REQUESTED) {
      if (resultCode == RESULT_OK) {

        // Get the new login information from preferences
        final SharedPreferences mPrefs =
            new ObscuredSharedPreferences(
                DataWalk.mContext,
                DataWalk.mContext.getSharedPreferences(USER_PREFS_KEY, Context.MODE_PRIVATE));
        loginName = mPrefs.getString(DataWalk.USERNAME_KEY, DEFAULT_USERNAME);
        loginPass = mPrefs.getString(DataWalk.PASSWORD_KEY, DEFAULT_USERNAME);

        // Set the UI to the new login name
        loggedInAs.setText(getResources().getString(R.string.logged_in_as) + " " + loginName);
      } else {
        // A lo
        // Set the UI to say you aren't logged in
        // TODO What if you are still logged in as default?
        // loggedInAs.setText(getResources().getString(R.string.logged_in_as + ""+ loginName));
        loggedInAs.setText(getResources().getString(R.string.logged_in_as) + " " + loginName);
      }
    }
  } // End of onActivityResult