/*
  * (non-Javadoc)
  * @see android.app.Activity#onPause()
  */
 @Override
 protected void onPause() {
   super.onPause();
   mViewFlipper.stopFlipping();
   mGraphTimeSpeed.clearData();
   mGraphDistanceSpeed.clearData();
   mGraphTimeAltitude.clearData();
   mGraphDistanceAltitude.clearData();
   ContentResolver resolver = this.getContentResolver();
   resolver.unregisterContentObserver(this.mTrackObserver);
 }
  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle load) {
    super.onCreate(load);
    mUnits =
        new UnitsI18n(
            this,
            new UnitsI18n.UnitsChangeListener() {
              public void onUnitsChange() {
                drawTrackingStatistics();
              }
            });
    setContentView(R.layout.statistics);

    mViewFlipper = (ViewFlipper) findViewById(R.id.flipper);
    mViewFlipper.setDrawingCacheEnabled(true);
    mSlideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
    mSlideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
    mSlideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
    mSlideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);

    mGraphTimeSpeed = (GraphCanvas) mViewFlipper.getChildAt(0);
    mGraphDistanceSpeed = (GraphCanvas) mViewFlipper.getChildAt(1);
    mGraphTimeAltitude = (GraphCanvas) mViewFlipper.getChildAt(2);
    mGraphDistanceAltitude = (GraphCanvas) mViewFlipper.getChildAt(3);

    mGraphTimeSpeed.setType(GraphCanvas.TIMESPEEDGRAPH);
    mGraphDistanceSpeed.setType(GraphCanvas.DISTANCESPEEDGRAPH);
    mGraphTimeAltitude.setType(GraphCanvas.TIMEALTITUDEGRAPH);
    mGraphDistanceAltitude.setType(GraphCanvas.DISTANCEALTITUDEGRAPH);

    mGestureDetector = new GestureDetector(new MyGestureDetector());

    maxSpeedView = (TextView) findViewById(R.id.stat_maximumspeed);
    mAscensionView = (TextView) findViewById(R.id.stat_ascension);
    mElapsedTimeView = (TextView) findViewById(R.id.stat_elapsedtime);
    overallavgSpeedView = (TextView) findViewById(R.id.stat_overallaveragespeed);
    avgSpeedView = (TextView) findViewById(R.id.stat_averagespeed);
    distanceView = (TextView) findViewById(R.id.stat_distance);
    starttimeView = (TextView) findViewById(R.id.stat_starttime);
    endtimeView = (TextView) findViewById(R.id.stat_endtime);
    waypointsView = (TextView) findViewById(R.id.stat_waypoints);

    if (load != null && load.containsKey(TRACKURI)) {
      mTrackUri = Uri.withAppendedPath(Tracks.CONTENT_URI, load.getString(TRACKURI));
    } else {
      mTrackUri = this.getIntent().getData();
    }
  }
  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle load) {
    super.onCreate(load);
    mUnits =
        new UnitsI18n(
            this,
            new UnitsI18n.UnitsChangeListener() {
              public void onUnitsChange() {
                drawTrackingStatistics();
              }
            });
    setContentView(R.layout.statistics);

    mGraphView = (GraphCanvas) findViewById(R.id.graph_canvas);
    mGraphView.setOnClickListener(mGraphOnClickListener);

    maxSpeedView = (TextView) findViewById(R.id.stat_maximumspeed);
    minAltitudeView = (TextView) findViewById(R.id.stat_minimalaltitide);
    maxAltitudeView = (TextView) findViewById(R.id.stat_maximumaltitude);
    overallavgSpeedView = (TextView) findViewById(R.id.stat_overallaveragespeed);
    avgSpeedView = (TextView) findViewById(R.id.stat_averagespeed);
    distanceView = (TextView) findViewById(R.id.stat_distance);
    starttimeView = (TextView) findViewById(R.id.stat_starttime);
    endtimeView = (TextView) findViewById(R.id.stat_endtime);
    waypointsView = (TextView) findViewById(R.id.stat_waypoints);

    if (load != null && load.containsKey(TRACKURI)) {
      mTrackUri = Uri.withAppendedPath(Tracks.CONTENT_URI, load.getString(TRACKURI));
    } else {
      mTrackUri = this.getIntent().getData();
    }
    drawTrackingStatistics();
  }
 public void onClick(View v) {
   int id = v.getId();
   switch (id) {
     case R.id.graphtype_distancealtitude:
       mGraphView.setType(GraphCanvas.DISTANCEALTITUDEGRAPH);
       break;
     case R.id.graphtype_distancespeed:
       mGraphView.setType(GraphCanvas.DISTANCESPEEDGRAPH);
       break;
     case R.id.graphtype_timealtitude:
       mGraphView.setType(GraphCanvas.TIMEALTITUDEGRAPH);
       break;
     case R.id.graphtype_timespeed:
       mGraphView.setType(GraphCanvas.TIMESPEEDGRAPH);
       break;
     default:
       break;
   }
   dismissDialog(DIALOG_GRAPHTYPE);
 }
 @Override
 protected void onRestoreInstanceState(Bundle load) {
   if (load != null) {
     super.onRestoreInstanceState(load);
   }
   if (load != null && load.containsKey(GRAPH_TYPE)) {
     mGraphView.setType(load.getInt(GRAPH_TYPE));
   }
   if (load != null && load.containsKey(TRACKURI)) {
     mTrackUri = Uri.withAppendedPath(Tracks.CONTENT_URI, load.getString(TRACKURI));
   }
 }
  public void finishedCalculations(StatisticsCalulator calculated) {
    mGraphTimeSpeed.setData(mTrackUri, calculated);
    mGraphDistanceSpeed.setData(mTrackUri, calculated);
    mGraphTimeAltitude.setData(mTrackUri, calculated);
    mGraphDistanceAltitude.setData(mTrackUri, calculated);

    mViewFlipper.postInvalidate();

    maxSpeedView.setText(calculated.getMaxSpeedText());
    mElapsedTimeView.setText(calculated.getDurationText());
    mAscensionView.setText(calculated.getAscensionText());
    overallavgSpeedView.setText(calculated.getOverallavgSpeedText());
    avgSpeedView.setText(calculated.getAvgSpeedText());
    distanceView.setText(calculated.getDistanceText());
    starttimeView.setText(Long.toString(calculated.getStarttime()));
    endtimeView.setText(Long.toString(calculated.getEndtime()));
    String titleFormat = getString(R.string.stat_title);
    setTitle(String.format(titleFormat, calculated.getTracknameText()));
    waypointsView.setText(calculated.getWaypointsText());

    calculating = false;
  }
  private void drawTrackingStatistics() {
    calculating = true;
    String overallavgSpeedText = "Unknown";
    String avgSpeedText = "Unknown";
    String maxSpeedText = "Unknown";
    String maxAltitudeText = "Unknown";
    String minAltitudeText = "Unknown";
    String tracknameText = "Unknown";
    String waypointsText = "Unknown";
    String distanceText = "Unknown";
    long starttime = 0;
    long endtime = 0;
    double maxSpeeddb = 0;
    double maxAltitude = 0;
    double minAltitude = 0;
    double distanceTraveled = 0f;
    long duration = 1;
    long overallduration = 1;

    ContentResolver resolver = this.getApplicationContext().getContentResolver();

    Cursor waypointsCursor = null;
    try {
      waypointsCursor =
          resolver.query(
              Uri.withAppendedPath(mTrackUri, "waypoints"),
              new String[] {
                "max  (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")",
                "max  (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")",
                "min  (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")",
                "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")"
              },
              null,
              null,
              null);
      if (waypointsCursor.moveToLast()) {
        maxSpeeddb = waypointsCursor.getDouble(0);
        maxAltitude = waypointsCursor.getDouble(1);
        minAltitude = waypointsCursor.getDouble(2);
        long nrWaypoints = waypointsCursor.getLong(3);
        waypointsText = nrWaypoints + "";
      }
    } finally {
      if (waypointsCursor != null) {
        waypointsCursor.close();
      }
    }
    Cursor trackCursor = null;
    try {
      trackCursor = resolver.query(mTrackUri, new String[] {Tracks.NAME}, null, null, null);
      if (trackCursor.moveToLast()) {
        tracknameText = trackCursor.getString(0);
      }
    } finally {
      if (trackCursor != null) {
        trackCursor.close();
      }
    }
    Cursor segments = null;
    Location lastLocation = null;
    Location currentLocation = null;
    try {
      Uri segmentsUri = Uri.withAppendedPath(this.mTrackUri, "segments");
      segments = resolver.query(segmentsUri, new String[] {Segments._ID}, null, null, null);
      if (segments.moveToFirst()) {
        do {
          long segmentsId = segments.getLong(0);
          Cursor waypoints = null;
          try {
            Uri waypointsUri = Uri.withAppendedPath(segmentsUri, segmentsId + "/waypoints");
            waypoints =
                resolver.query(
                    waypointsUri,
                    new String[] {
                      Waypoints._ID, Waypoints.TIME, Waypoints.LONGITUDE, Waypoints.LATITUDE
                    },
                    null,
                    null,
                    null);
            if (waypoints.moveToFirst()) {
              do {
                if (starttime == 0) {
                  starttime = waypoints.getLong(1);
                }
                currentLocation = new Location(this.getClass().getName());
                currentLocation.setTime(waypoints.getLong(1));
                currentLocation.setLongitude(waypoints.getDouble(2));
                currentLocation.setLatitude(waypoints.getDouble(3));
                if (lastLocation != null) {
                  distanceTraveled += lastLocation.distanceTo(currentLocation);
                  duration += currentLocation.getTime() - lastLocation.getTime();
                }
                lastLocation = currentLocation;

              } while (waypoints.moveToNext());
              endtime = lastLocation.getTime();
              overallduration = endtime - starttime;
            }
          } finally {
            if (waypoints != null) {
              waypoints.close();
            }
          }
          lastLocation = null;
        } while (segments.moveToNext());
      }
    } finally {
      if (segments != null) {
        segments.close();
      }
    }

    mGraphView.setData(
        mTrackUri,
        starttime,
        endtime,
        distanceTraveled,
        minAltitude,
        maxAltitude,
        maxSpeeddb,
        mUnits);

    maxSpeeddb = mUnits.conversionFromMetersPerSecond(maxSpeeddb);
    maxAltitude = mUnits.conversionFromMeterToSmall(maxAltitude);
    minAltitude = mUnits.conversionFromMeterToSmall(minAltitude);
    double overallavgSpeedfl =
        mUnits.conversionFromMeterAndMiliseconds(distanceTraveled, overallduration);
    double avgSpeedfl = mUnits.conversionFromMeterAndMiliseconds(distanceTraveled, duration);
    distanceTraveled = mUnits.conversionFromMeter(distanceTraveled);
    avgSpeedText = String.format("%.2f %s", avgSpeedfl, mUnits.getSpeedUnit());
    overallavgSpeedText = String.format("%.2f %s", overallavgSpeedfl, mUnits.getSpeedUnit());
    distanceText = String.format("%.2f %s", distanceTraveled, mUnits.getDistanceUnit());
    maxSpeedText = String.format("%.2f %s", maxSpeeddb, mUnits.getSpeedUnit());
    minAltitudeText = String.format("%.0f %s", minAltitude, mUnits.getDistanceSmallUnit());
    maxAltitudeText = String.format("%.0f %s", maxAltitude, mUnits.getDistanceSmallUnit());

    maxSpeedView.setText(maxSpeedText);
    maxAltitudeView.setText(maxAltitudeText);
    minAltitudeView.setText(minAltitudeText);
    overallavgSpeedView.setText(overallavgSpeedText);
    avgSpeedView.setText(avgSpeedText);
    distanceView.setText(distanceText);
    starttimeView.setText(Long.toString(starttime));
    endtimeView.setText(Long.toString(endtime));
    String titleFormat = getString(R.string.stat_title);
    setTitle(String.format(titleFormat, tracknameText));
    waypointsView.setText(waypointsText);

    calculating = false;
  }
 @Override
 protected void onSaveInstanceState(Bundle save) {
   super.onSaveInstanceState(save);
   save.putInt(GRAPH_TYPE, mGraphView.getType());
   save.putString(TRACKURI, mTrackUri.getLastPathSegment());
 }