package com.sebnarware.avalanche;

import java.util.HashMap;

import org.json.*;

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

import com.google.android.maps.GeoPoint;
import com.loopj.android.http.JsonHttpResponseHandler;

public class DataManager {
	
    private static final String TAG = "DataManager";

	private TimeframeMode timeframeMode;
	private NetworkEngine networkEngine = new NetworkEngine();
	private HashMap<String, RegionData> regions = new HashMap<String, RegionData>();
	
	public DataManager() {
        this.timeframeMode = TimeframeMode.Today;
	}

	public TimeframeMode getTimeframeMode() {
		return timeframeMode;
	}

	public void setTimeframeMode(TimeframeMode timeframeMode) {
		this.timeframeMode = timeframeMode;
	}

	public void loadRegionsAndForecasts(final DataListener dataListener, final Context context) {
		
		networkEngine.loadRegions(new JsonHttpResponseHandler() {
	        @Override
	        public void onSuccess(JSONArray response) {

	        	Log.i(TAG, "loadRegions network success");
	        	
	        	try {
	        		// parse out each region
	        		for (int i = 0; i < response.length(); i++) {
	        			JSONObject regionJSON = response.getJSONObject(i);
	        			String regionId = regionJSON.getString("regionId");
	        			String displayName = regionJSON.getString("displayName");
	        			String URL = regionJSON.getString("URL");
	        			
	        			JSONArray pointsJSON = regionJSON.getJSONArray("points");
	        			GeoPoint[] polygon = new GeoPoint[pointsJSON.length()];
	        			for (int j = 0; j < pointsJSON.length(); j++) {
	        				JSONObject pointJSON = pointsJSON.getJSONObject(j);
	        				double lat = pointJSON.getDouble("lat");
	        				double lon = pointJSON.getDouble("lon");
	        				polygon[j] = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
	        			}
	        			
	        			// create the region data, and add it to our set
	        			RegionData regionData = new RegionData(regionId, displayName, URL, polygon);
	        			regions.put(regionId, regionData);
		        		Log.d(TAG, "loadRegions created region: " + regionId);
		        		
		        		// call the listener
		        		dataListener.regionAdded(regionData);
	        		}
	        		
	        		Log.i(TAG, "loadRegions total count of regions created: " + regions.size());
	        		
	        		// now, go load the forecasts
	        		loadForecasts(dataListener, context);

	        	} catch (JSONException e) {
	            	Log.w(TAG, "loadRegions JSON parsing failure; error: " + e.toString());
	        	}
	        }
	        
	        @Override
	        public void onFailure(Throwable error, String content) {
	        	Log.w(TAG, "loadRegions network failure; error: " + error.toString() + "; content: " + content);
	        }
	    });
	}

	public void loadForecasts(final DataListener dataListener, final Context context) {

		networkEngine.loadForecasts(new JsonHttpResponseHandler() {
	        @Override
	        public void onSuccess(JSONArray response) {

	        	Log.i(TAG, "loadForecasts network success");
	        	
	        	try {
	        		// parse out each region forecast
	        		int validForecastCount = 0;
	        		for (int i = 0; i < response.length(); i++) {
	        			JSONObject regionJSON = response.getJSONObject(i);
	        			String regionId = regionJSON.getString("regionId");
	        			
	        			// NOTE forecast may be null, if no forecast is currently available for this region
	        			if (!regionJSON.isNull("forecast")) {
	        				
	        				JSONArray forecastJSON = regionJSON.getJSONArray("forecast");
	        			
		        			ForecastDay[] forecast = new ForecastDay[forecastJSON.length()];
		        			for (int j = 0; j < forecastJSON.length(); j++) {
		        				JSONObject forecastDayJSON = forecastJSON.getJSONObject(j);
		        				String date = forecastDayJSON.getString("date");
		        				int aviLevel = forecastDayJSON.getInt("aviLevel");
		        				forecast[j] = new ForecastDay(date, aviLevel);
		        			}
		        			
		        			// set the forecast on the region
		        			RegionData regionData = regions.get(regionId);
		        			regionData.setForecast(forecast);
			        		Log.d(TAG, "loadForecasts loaded forecast for region: " + regionId);
			        		validForecastCount++;
			        		
			        		// call the listener
			        		dataListener.forecastUpdated(regionData);
	        			}
	        		}
	        		
	        		Log.i(TAG, "loadForecasts total count of non-null forecasts received: " + validForecastCount);

	        	} catch (JSONException e) {
	            	Log.w(TAG, "loadForecasts JSON parsing failure; error: " + e.toString());
	        	}
	        }
	        
	        @Override
	        public void onFailure(Throwable error, String content) {
	        	Log.w(TAG, "loadForecasts network failure; error: " + error.toString() + "; content: " + content);
	        }
	    });
	}

}

@@ -3414,32 +3414,76 @@
 );%0A%09        %09%09%09%0A
+%09        %09%09%09ForecastDay%5B%5D forecast = null; %0A
 %09        %09%09%09// N
@@ -3723,38 +3723,24 @@
 %09        %09%09%09
-ForecastDay%5B%5D 
 forecast = n
@@ -4123,69 +4123,92 @@
 %09%09%7D%0A
-%09%09        %09%09%09%0A%09%09        %09%09%09// set the forecast on the
+%0A%09%09%09        %09%09Log.d(TAG, %22loadForecasts loaded forecast for region: %22 +
  region
-%0A
+Id);%0A%09
 %09%09  
@@ -4219,57 +4219,30 @@
   %09%09
-%09RegionData regionData = regions.get(regionId)
+validForecastCount++
 ;%0A
-%09
 %09   
@@ -4253,41 +4253,16 @@
  %09%09%09
-regionData.setForecast(forecast);
+%7D else %7B
 %0A%09%09%09
@@ -4289,38 +4289,36 @@
  %22loadForecasts 
-loaded
+null
  forecast for re
@@ -4343,43 +4343,185 @@
 );%0A%09
-%09%09        %09%09validForecastCount++
+        %09%09%09%7D%0A%09        %09%09%09%0A%09        %09%09%09// set the forecast on the region%0A%09        %09%09%09RegionData regionData = regions.get(regionId);%0A%09        %09%09%09regionData.setForecast(forecast)
 ;%0A
-%09
 %09%09  
@@ -4529,17 +4529,16 @@
      %09%09%0A
-%09
 %09%09      
@@ -4564,17 +4564,16 @@
 tener%0A%09%09
-%09
         
@@ -4616,30 +4616,16 @@
 nData);%0A
-%09        %09%09%09%7D%0A
 %09       

fix bug where if forecast for a region was null, we didn't draw it