/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.android.apps.mytracks.maps;

import static com.google.android.apps.mytracks.Constants.TAG;

import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.mytracks.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.util.Log;


/**
 * A dynamic speed path descriptor.
 *
 * @author Vangelis S.
 */
public class DynamicSpeedTrackPathDescriptor 
  implements TrackPathDescriptor, OnSharedPreferenceChangeListener {
  private int slowSpeed;
  private int normalSpeed;
  private int speedMargin;
  private double averageMovingSpeed;
  private final Context context;
  
  public DynamicSpeedTrackPathDescriptor(Context context){
    this.context = context;
    SharedPreferences prefs = context.getSharedPreferences(
        Constants.SETTINGS_NAME, Context.MODE_PRIVATE);

    if (prefs == null) {
      speedMargin = 25;
      return;
    }
    prefs.registerOnSharedPreferenceChangeListener(this);

    speedMargin = Integer.parseInt(prefs.getString(
        context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "25"));
  }
  
  /**
   * Get the slow speed calculated based on the % below the average speed.
   * @return The speed limit considered as slow.
   */
  public int getSlowSpeed()
  {
    slowSpeed = (int) (averageMovingSpeed - (averageMovingSpeed * speedMargin / 100)); 
    return slowSpeed;
  }
  
  /**
   * Get the medium speed calculated based on the % above the average speed.
   * @return The speed limit considered as normal.
   */
  public int getNormalSpeed()
  {
    normalSpeed = (int) (averageMovingSpeed + (averageMovingSpeed * speedMargin / 100)); 
    return normalSpeed;
  }
  
  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Log.d(TAG, "DynamicSpeedTrackPathDescriptor: onSharedPreferences changed " + key);
    if (key == null 
    	|| !key.equals(context.getString(R.string.track_color_mode_dynamic_speed_variation_key))) {
      return;
    }
    SharedPreferences prefs = context.getSharedPreferences(
        Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
    	
    if (prefs == null) {
      speedMargin = 25;
      return;
    }
        
    speedMargin = 
        Integer.parseInt(
    	    prefs.getString(
    	        context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "25"));
    }

  @Override
  public boolean needsRedraw() {
    SharedPreferences prefs = context.getSharedPreferences(
        Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
    long currentTrackId = prefs.getLong(context.getString(R.string.selected_track_key), -1);
    if(currentTrackId == -1) {
      // Could not find track. 
      return false; 
    }
    Track track = MyTracksProviderUtils.Factory.get(context).getTrack(currentTrackId);
    TripStatistics stats = track.getStatistics();
    double newaverageSpeed = (int) Math.floor(stats.getAverageMovingSpeed() * 3.6);
    
    if(averageMovingSpeed == 0) {
      averageMovingSpeed = newaverageSpeed;
      return true;
    }
    
    double difference = Math.max(averageMovingSpeed, newaverageSpeed);

    if (difference == 0.0) {
      difference = 0.0;
    } else {
      difference = Math.abs(averageMovingSpeed - newaverageSpeed) / difference * 100;
    }
    if(difference >= 20) {
      averageMovingSpeed = newaverageSpeed;
      return true;
    }
    return false;
  }
}
@@ -1339,16 +1339,70 @@
 tener %7B%0A
+  %0A  private static int DEFAULT_SPEED_MARGIN = 25;%0A  %0A
   privat
@@ -1786,34 +1786,52 @@
   speedMargin = 
-25
+DEFAULT_SPEED_MARGIN
 ;%0A      return;%0A
@@ -1917,138 +1917,398 @@
 n = 
-Integer.parseInt(prefs.getString(%0A        context.getString(R.string.track_color_mode_dynamic_speed_variation_key), %2225%22))
+getSpeedMargin(prefs);%0A  %7D%0A%0A  private int getSpeedMargin(SharedPreferences sharedPreferences) %7B%0A    String key = context.getString(R.string.track_color_mode_dynamic_speed_variation_key);%0A    String percentage = sharedPreferences.getString(key, DEFAULT_SPEED_MARGIN + %22%22);%0A    if (percentage.isEmpty()) %7B%0A      return DEFAULT_SPEED_MARGIN
 ;%0A
+  
   %7D%0A  
+  return Integer.parseInt(percentage);%0A  %7D%0A
 %0A  /
@@ -3379,18 +3379,36 @@
 argin = 
-25
+DEFAULT_SPEED_MARGIN
 ;%0A      
@@ -3421,24 +3421,16 @@
 ;%0A    %7D%0A
-        
 %0A    spe
@@ -3444,158 +3444,31 @@
 n = 
-%0A        Integer.parseInt(%0A    %09    prefs.getString(%0A    %09        context.getString(R.string.track_color_mode_dynamic_speed_variation_key), %2225%22)
+getSpeedMargin(prefs
 );%0A
-  
   %7D%0A

Fix crash in issue 680.