Newer
Older
mountainnavigation / app / src / main / java / de / apps4ics / mountainnavigation / MainActivity.java
package de.apps4ics.mountainnavigation;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.survivingwithandroid.weather.lib.WeatherClient;
import com.survivingwithandroid.weather.lib.WeatherCode;
import com.survivingwithandroid.weather.lib.WeatherConfig;
import com.survivingwithandroid.weather.lib.exception.WeatherLibException;
import com.survivingwithandroid.weather.lib.exception.WeatherProviderInstantiationException;
import com.survivingwithandroid.weather.lib.model.DayForecast;
import com.survivingwithandroid.weather.lib.model.HistoricalWeather;
import com.survivingwithandroid.weather.lib.model.Weather;
import com.survivingwithandroid.weather.lib.model.WeatherForecast;
import com.survivingwithandroid.weather.lib.provider.openweathermap.OpenweathermapProviderType;
import com.survivingwithandroid.weather.lib.request.WeatherRequest;

import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.OverlayItem;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import de.apps4ics.mountainnavigation.adapters.ImageListAdapter;
import de.apps4ics.mountainnavigation.handlers.DatabaseHandler;
import de.apps4ics.mountainnavigation.handlers.PoiHandler;
import de.apps4ics.mountainnavigation.pois.DbGeoPoint;
import de.apps4ics.mountainnavigation.pois.Fountain;
import de.apps4ics.mountainnavigation.pois.Poi;
import de.apps4ics.mountainnavigation.pois.Types;

public class MainActivity extends AppCompatActivity implements LocationListener {

    public static final String TAG = "MountainNavigation";
    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */

    private CharSequence mTitle;
    private CharSequence mDrawerTitle;
    private static final int GPS_MIN_TIME = 5000;
    private static final int GPS_MIN_DIST = 5;
    private static final String API_KEY = "fd4034defae557fd5f2fdaaf73c3402c";
    private static ConnectivityManager cm;
    private static TelephonyManager tm;
    private static WifiManager wm;
    private static NetworkInfo activeNetwork;
    private static int networkStrength;
    public static final int MAX_WIFI_LEVELS = 5;

    public static SimpleDateFormat df_hm;
    public static SimpleDateFormat df_full;

    private Resources res;
    private FloatingActionButton fab;

    private Weather todaysWeather;
    private Weather tomorrowsWeather;
    private HistoricalWeather histWeather;
    private DayForecast todaysForecast;
    private DayForecast tomorrowsForecast;
    private WeatherClient weatherClient;
    private static Integer[] severeWeatherCodes;
    private static float minHotTemp;
    private static float maxColdTemp;
    private static float minWindySpeed;
    private boolean showWeatherHints;

    private DatabaseHandler dbHandler;
    private PoiHandler poiHandler;

    private static MapView mapView;
    private IMapController mapController;
    public static int ZOOM_LEVEL;

    private ActionBarDrawerToggle drawerToggle;
    private DrawerLayout drawerLayout;
    private ListView listView;

    public static ArrayList<OverlayItem> pathMarkers;
    public static OverlayItem imageMarker;

    private String provider;
    private static Location mLocation;
    private LocationManager locationManager;

    private static List<Location> foundLocations;

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

        res = getResources();
        pathMarkers = new ArrayList<>();

        cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        activeNetwork = cm.getActiveNetworkInfo();
        networkStrength = 0;
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        tm.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        wm = (WifiManager) getSystemService(WIFI_SERVICE);

        df_hm = new SimpleDateFormat(res.getString(R.string.date_format_hm));
        df_full = new SimpleDateFormat(res.getString(R.string.date_format_full));

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.container);

        ZOOM_LEVEL = 18;
        mapView = new MapView(getApplicationContext());
        mapView.setTileSource(TileSourceFactory.MAPNIK);
        mapView.setBuiltInZoomControls(true);
        mapView.setMultiTouchControls(true);
        mapController = mapView.getController();
        mapController.setZoom(ZOOM_LEVEL);
        mapController.setCenter(new GeoPoint(48.52, 9.055));

        dbHandler = new DatabaseHandler(this);
        poiHandler = new PoiHandler(this, res, mapView);

        foundLocations = new ArrayList<>();

        relativeLayout.addView(mapView);

        mTitle = mDrawerTitle = getTitle();

        initGps();

        WeatherClient.ClientBuilder weatherBuilder = new WeatherClient.ClientBuilder();
        WeatherConfig weatherConfig = new WeatherConfig();
        weatherConfig.unitSystem = WeatherConfig.UNIT_SYSTEM.M;
        weatherConfig.ApiKey = API_KEY;
        weatherConfig.lang = res.getString(R.string.lang_identifier);
        weatherConfig.numDays = 2;

        minWindySpeed = 8; //http://www.wettergefahren-fruehwarnung.de/Artikel/beaufort.html
        if(weatherConfig.unitSystem.equals(WeatherConfig.UNIT_SYSTEM.I)){
            minHotTemp = celsiusToFahrenheit(30);
            maxColdTemp = celsiusToFahrenheit(10);
        } else {
            minHotTemp = 30;
            maxColdTemp = 10;
        }

        showWeatherHints = true;

        //TODO split into severe weather and foggy, windy, sunny, ...
        severeWeatherCodes = new Integer[]{
                WeatherCode.TORNADO.getCode(),
                WeatherCode.TROPICAL_STORM.getCode(),
                WeatherCode.HURRICANE.getCode(),
                WeatherCode.SEVERE_THUNDERSTORMS.getCode(),
                WeatherCode.THUNDERSTORMS.getCode(),
                WeatherCode.MIXED_RAIN_SNOW.getCode(),
                WeatherCode.MIXED_RAIN_SLEET.getCode(),
                WeatherCode.MIXED_SNOW_SLEET.getCode(),
                WeatherCode.FREEZING_DRIZZLE.getCode(),
                WeatherCode.FREEZING_RAIN.getCode(),
                WeatherCode.HEAVY_SHOWERS.getCode(),
                WeatherCode.SNOW_FLURRIES.getCode(),
                WeatherCode.LIGHT_SNOW_SHOWERS.getCode(),
                WeatherCode.BLOWING_SNOW.getCode(),
                WeatherCode.SNOW.getCode(),
                WeatherCode.HAIL.getCode(),
                WeatherCode.SLEET.getCode(),
                WeatherCode.FOGGY.getCode(),
                WeatherCode.HAZE.getCode(),
                WeatherCode.WINDY.getCode(),
                WeatherCode.COLD.getCode(),
                WeatherCode.SUNNY.getCode(),
                WeatherCode.MIXED_RAIN_AND_HAIL.getCode(),
                WeatherCode.ISOLATED_THUNDERSTORMS.getCode(),
                WeatherCode.SCATTERED_THUNDERSTORMS.getCode(),
                WeatherCode.HEAVY_SNOW.getCode(),
                WeatherCode.SCATTERED_SNOW_SHOWERS.getCode(),
                WeatherCode.THUNDERSHOWERS.getCode(),
                WeatherCode.SNOW_SHOWERS.getCode(),
                WeatherCode.ISOLATED_THUDERSHOWERS.getCode(),
                WeatherCode.TORNADO.getCode()
        };

        weatherClient = null;
        try {
            weatherClient = weatherBuilder.attach(getApplicationContext())
                    .provider(new OpenweathermapProviderType())
                    .httpClient(com.survivingwithandroid.weather.lib.client.okhttp.WeatherDefaultClient.class)
                    .config(weatherConfig)
                    .build();
        } catch (WeatherProviderInstantiationException e) {
            e.printStackTrace();
        }

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mLocation == null){
                    InformDialog informDialog = new InformDialog(getString(R.string.inform_title), getString(R.string.inform_gps_pos_not_found));
                    informDialog.show(getFragmentManager(), "Inform Dialog");
                    return;
                }
                PoiHandler.AddPoiDialog addPoiDialog = poiHandler.createAddPoiDialog();
                addPoiDialog.show(getFragmentManager(), "Add POI Dialog");
            }
        });
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        listView = (ListView) findViewById(R.id.navigation_drawer);

        drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

//        listView.setItemsCanFocus(false);
        ImageListAdapter adapter = new ImageListAdapter(MainActivity.this, PoiHandler.getEntries(), PoiHandler.getEntryImgs(), false);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TableLayout layout = (TableLayout) view;
                toggleDrawerItems(layout, position);
                //drawerLayout.closeDrawers(); //TODO close drawer on click?
            }
        });

        drawerLayout.setDrawerListener(drawerToggle);

        double _lat = 48.52;
        double _lon = 9.055;
        double _alt = 350;
        long _time = System.currentTimeMillis() / 1000;
        DbGeoPoint dbgp = new DbGeoPoint(_lat, _lon, _alt, _time);
        long gp_id = dbHandler.addPoi(dbgp);
        dbgp.setId(gp_id);
        Fountain fountain = new Fountain(0, 2, dbgp);
        long f_id = dbHandler.addPoi(fountain);
    }

    public static float celsiusToFahrenheit(float c) {
        return c * 9.0f/5.0f + 32;
    }

    public static float fahrenheitToCelsius(float f) {
        return (f - 32.0f) * 5.0f/9.0f;
    }

    private void toggleDrawerItems(TableLayout layout, int position){
        TableRow tr = (TableRow) layout.getChildAt(0); //TODO is tablerow?
        TextView tv = null;
        ImageView iv = null;
        for(int i=0; i<tr.getChildCount(); ++i){
            View v = tr.getChildAt(i);
            try {
                tv = (TextView) v;
            } catch(ClassCastException cce){
                //Log.e(TAG, "Could not cast " + v.getClass().toString() + " to TextView!");
            }
            try {
                iv = (ImageView) v;
            } catch(ClassCastException cce){
                //Log.e(TAG, "Could not cast " + v.getClass().toString() + " to ImageView!");
            }
        }
        if(tv == null || iv == null){
            Log.e(TAG, "Neither TextView nor ImageView can be null!");
            return;
        }
        int type = getType(position);
        if(iv.getTag() == null || iv.getTag() == "disabled"){
            iv.setColorFilter(null);
            iv.setTag("");
            tv.setTextColor(res.getColor(R.color.text_color_selected));
            String title = PoiHandler.getEntries()[position];
            List<Marker> markers = poiHandler.getPoiIcons(type, title);
            mapView.getOverlays().addAll(markers);
            mapView.invalidate();
        } else {
            iv.setColorFilter(res.getColor(R.color.icon_unselected_gray));
            iv.setTag("disabled");
            tv.setTextColor(res.getColor(R.color.text_color));
            Toaster("You disabled " + PoiHandler.getEntries()[position]);
            poiHandler.disablePois(type);
            mapView.invalidate();
        }
    }

    public static List<Location> getFoundLocations() {
        return foundLocations;
    }

    public static int getPos(int type){
        int pos;
        switch(type){
            case Types.FOUNTAIN:
                pos = 0;
                break;
            case Types.PATH:
                pos = 1;
                break;
            case Types.HUT:
                pos = 2;
                break;
            case Types.PEAK:
                pos = 3;
                break;
            case Types.BREAK_POINT:
                pos = 4;
                break;
            case Types.TRASH_BIN:
                pos = 5;
                break;
            case Types.PIC:
                pos = 6;
                break;
            case Types.CELL_RECEPTION:
                pos = 7;
                break;
            case Types.WIFI:
                pos = 8;
                break;
            case Types.LIFT:
                pos = 9;
                break;
            default:
                pos = 0;
                break;
        }
        return pos;
    }

    public static int getType(int position){
        int type;
        switch (position){
            case 0:
                type = Types.FOUNTAIN;
                break;
            case 1:
                type = Types.PATH;
                break;
            case 2:
                type = Types.HUT;
                break;
            case 3:
                type = Types.PEAK;
                break;
            case 4:
                type = Types.BREAK_POINT;
                break;
            case 5:
                type = Types.TRASH_BIN;
                break;
            case 6:
                type = Types.PIC;
                break;
            case 7:
                type = Types.CELL_RECEPTION;
                break;
            case 8:
                type = Types.WIFI;
                break;
            case 9:
                type = Types.LIFT;
                break;
            case 10:
                type = Types.GP;
                break;
            default:
                type = 0;
                break;
        }
        return type;
    }

    private String getTypeName(int type){
        String name = "";
        switch(type){
            case Types.FOUNTAIN:
                name = "fountain";
                break;
            case Types.PATH:
                name = "path";
                break;
            case Types.HUT:
                name = "hut";
                break;
            case Types.PEAK:
                name = "peak";
                break;
            case Types.BREAK_POINT:
                name = "break_point";
                break;
            case Types.TRASH_BIN:
                name = "trash_bin";
                break;
            case Types.PIC:
                name = "image";
                break;
            case Types.CELL_RECEPTION:
                name = "cell_reception";
                break;
            case Types.WIFI:
                name = "wifi";
                break;
            case Types.LIFT:
                name = "lift";
                break;
        }
        return name;
    }

    private void initGps(){
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean isLocationEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if(!isLocationEnabled){
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        mLocation = locationManager.getLastKnownLocation(provider);
    }

    private void Toaster(String text){
        Toaster(text, false);
    }

    private void Toaster(String text, boolean longDuration){
        if(longDuration) Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
        else Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    public static void Toaster(String text, Context context){
        Toaster(text, false, context);
    }

    public static void Toaster(String text, boolean longDuration, Context context) {
        if(longDuration) Toast.makeText(context, text, Toast.LENGTH_LONG).show();
        else Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static Location getLocation() { return mLocation; }

    public static MapView getMapView(){
        return mapView;
    }

    public DatabaseHandler getDbHandler(){
        return dbHandler;
    }

    public static ArrayList<OverlayItem> getPathMarkers(){
        return pathMarkers;
    }

    public static void setPathMarkers(ArrayList<OverlayItem> al){
        pathMarkers = al;
    }

    private static void setActiveNetwork(){
        activeNetwork = cm.getActiveNetworkInfo();
    }

    public static void setNetworkStrength(int strength){
        networkStrength = strength;
    }

    public static int getNetworkStrength() {
        return networkStrength;
    }

    private void addSimpleMarker(GeoPoint gp){
        Marker positionMarker = new Marker(mapView);
        positionMarker.setPosition(gp);
        positionMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
        positionMarker.setTitle(getString(R.string.osm_marker_title));
        positionMarker.setSnippet(String.format(getString(R.string.osm_marker_snippet), gp.getLatitude(), gp.getLongitude(), gp.getAltitude(), 0));
        mapView.getOverlays().add(positionMarker);
        mapView.invalidate();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLocation = location;
        if(mLocation == null) return;
        foundLocations.add(location);
        //poiHandler.updatePois();
        List<Poi> test = poiHandler.getPoisAround(location.getLatitude(), location.getLongitude(), 20);
        Log.d(TAG, "Get POIs around: " + location.toString());
        int i=1;
        for(Poi p : test) {
            Log.d(TAG, "POI #" + (i++) + ": " + p.toString());
        }

        double lat = location.getLatitude();
        double lon = location.getLongitude();
        GeoPoint gp = new GeoPoint(lat, lon);

        addSimpleMarker(gp);

        mapController.setCenter(gp);

        //TODO Move this to the not-yet-implemented upload method
        weatherClient.getForecastWeather(new WeatherRequest(lon, lat), new WeatherClient.ForecastWeatherEventListener() {
            @Override
            public void onWeatherRetrieved(WeatherForecast forecast) {
                todaysForecast = forecast.getForecast(0);
                tomorrowsForecast = forecast.getForecast(1);
                todaysWeather = todaysForecast.weather;
                tomorrowsWeather = tomorrowsForecast.weather;
                Log.d(TAG, "City [" + todaysWeather.location.getCity() + "] Current temp: " + todaysWeather.temperature.getTemp());

                String title = String.format("Weather for %s in %s", todaysWeather.location.getCity(), todaysWeather.location.getCountry());
                String msg = String.format("%1$.1f%2$s (%3$.1f%4$s/%5$.1f%6$s)\nSunrise: %7$s\nSunset: %8$s\nWeatherCode: %9$d\nWeatherId: %10$d",
                        todaysForecast.forecastTemp.day,
                        forecast.getUnit().tempUnit,
                        todaysForecast.forecastTemp.min,
                        forecast.getUnit().tempUnit,
                        todaysForecast.forecastTemp.max,
                        forecast.getUnit().tempUnit,
                        df_hm.format(new Date(todaysWeather.location.getSunrise() * 1000)),
                        df_hm.format(new Date(todaysWeather.location.getSunset() * 1000)),
                        todaysWeather.currentCondition.getWeatherCode().getCode(),
                        todaysWeather.currentCondition.getWeatherId());
                //InformDialog informWeatherDialog = new InformDialog(title, msg);
                //informWeatherDialog.show(getFragmentManager(), "Inform Dialog");
                boolean isSevereWeather = isSevereWeather(todaysWeather.currentCondition.getWeatherCode().getCode());
                Log.d(TAG, title + ": " + msg);
                Log.d(TAG, "isSevereWeather? " + isSevereWeather);
                //TODO add more hints
                if (showWeatherHints) {
                    List<String> titles = new ArrayList<>();
                    List<String> descs = new ArrayList<>();
                    if (isSunny()) {
                        titles.add("Sunny");
                        descs.add("The weather might be sunny. You should take some suncream with you!");
                    }
                    if (isHot()) {
                        titles.add("Hot");
                        descs.add("It is hot outside. Remember to take enough to drink with you.");
                    }
                    if (isCold()) {
                        titles.add("Cold");
                        descs.add("The weather might be cold. You should take some warm clothes with you!");
                    }
                    if (isWindy()) {
                        titles.add("Windy");
                        descs.add("The weather might be windy. You should take some windproof clothes with you!");
                    }
                    if (isAfterSunset()) {
                        titles.add("Sunset");
                        descs.add("It is already after sunset. Better take a head lamp with you.");
                    }
                    if (titles.size() > 0 && descs.size() > 0) {
                        String[] titleArr = new String[titles.size()];
                        String[] descArr = new String[descs.size()];
                        titleArr = titles.toArray(titleArr);
                        descArr = descs.toArray(descArr);
                        WarningListAdapter warningAdapter = new WarningListAdapter(MainActivity.this, titleArr, descArr);
                        InformListDialog weatherHintDialog = new InformListDialog(getString(R.string.hint_dialog_title), warningAdapter);
                        weatherHintDialog.show(getFragmentManager(), "Warning Hint Dialog");
                    }
                }
                if (isSevereWeather) {
                    String warnMsg = String.format(getString(R.string.weather_warning_dialog_msg), todaysWeather.location.getCity(), todaysWeather.currentCondition.getWeatherCode().getLabel(getApplicationContext()));
                    InformDialog informAlertDialog = new InformDialog(getString(R.string.weather_warning_dialog_title), warnMsg);
                    informAlertDialog.show(getFragmentManager(), "Inform Dialog - Weather Warning");
                }
            }

            @Override
            public void onWeatherError(WeatherLibException wle) {
                Log.e(TAG, "Weather error - parsing data");
                wle.printStackTrace();
            }

            @Override
            public void onConnectionError(Throwable t) {
                Log.e(TAG, "Connection Error");
                t.printStackTrace();
            }
        });
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d(TAG, "onStatusChanged: " + provider + ", " + status);
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d(TAG, "onProviderEnabled: " + provider);
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d(TAG, "onProviderDisabled: " + provider);
    }

    private boolean isSevereWeather(int weatherCode){
        return Arrays.asList(severeWeatherCodes).contains(weatherCode);
    }

    private boolean isAfterSunset(){
        return isAfterSunset(System.currentTimeMillis());
    }

    private boolean isAfterSunset(long time){
        return time > (todaysWeather.location.getSunset() * 1000) && time < (tomorrowsWeather.location.getSunrise() * 1000);
    }

    private boolean isHot(){
        return todaysWeather.currentCondition.getWeatherCode().getCode() == WeatherCode.SUNNY.getCode() ||
                (todaysWeather.temperature.getTemp() >= minHotTemp || todaysWeather.temperature.getMaxTemp() >= minHotTemp);
    }

    private boolean isSunny(){
        return todaysWeather.currentCondition.getWeatherCode().getCode() == WeatherCode.SUNNY.getCode();
    }

    private boolean isCold(){
        return todaysWeather.currentCondition.getWeatherCode().getCode() == WeatherCode.COLD.getCode() ||
                (todaysWeather.temperature.getTemp() <= maxColdTemp || todaysWeather.temperature.getMinTemp() <= maxColdTemp);
    }

    private boolean isWindy(){
        return todaysWeather.currentCondition.getWeatherCode().getCode() == WeatherCode.WINDY.getCode() ||
                        (todaysWeather.wind.getSpeed() >= minWindySpeed);
    }

    private boolean isDark(long length){
        return isDark(System.currentTimeMillis(), length);
    }

    private boolean isDark(long time, long length){
        return isAfterSunset(time) || isAfterSunset(time + length);
    }

    private HistoricalWeather getWeather(float lat, float lon, long start, long end){
        Date startDate = new Date(start / 1000); //OWM uses seconds instead of milliseconds
        Date endDate = new Date(end / 1000);
        histWeather = null;
        weatherClient.getHistoricalWeather(new WeatherRequest(lon, lat), startDate, endDate, new WeatherClient.HistoricalWeatherEventListener() {
            @Override
            public void onWeatherRetrieved(HistoricalWeather historicalWeather) {
                //TODO check if it was sunny/rainy and set fountain options based on this
                histWeather = historicalWeather;
            }

            @Override
            public void onWeatherError(WeatherLibException wle) {
                Log.e(TAG, "Weather error - parsing data");
                wle.printStackTrace();
            }

            @Override
            public void onConnectionError(Throwable t) {
                    Log.e(TAG, "Connection Error");
                    t.printStackTrace();
            }
        });
        return histWeather;
    }

    public class InformDialog extends DialogFragment {
        private String title;
        private String msg;

        public InformDialog(String title, String msg){
            this.title = title;
            this.msg = msg;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(title)
                    .setMessage(msg)
                    .setCancelable(false)
                    //.setIcon(res.getDrawable(R.mipmap.ic_info_icon))
                    .setPositiveButton(R.string.inform_positive_button, null);
            return builder.create();
        }
    }

    public class InformListDialog extends DialogFragment {
        private String title;
        private ListAdapter adapter;

        public InformListDialog(String title, ListAdapter adapter){
            this.title = title;
            this.adapter = adapter;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(title)
                    .setAdapter(adapter, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //nothing to do...
                        }
                    })
                    .setCancelable(false)
                            //.setIcon(res.getDrawable(R.mipmap.ic_info_icon))
                    .setPositiveButton(R.string.inform_positive_button, null);
            return builder.create();
        }
    }

    public static NetworkInfo getActiveNetwork() {
        return activeNetwork;
    }

    public static WifiManager getWifiManager() {
        return wm;
    }

    public static TelephonyManager getTelephonyManager() {
        return tm;
    }

    public static boolean hasInternet() {
        setActiveNetwork();
        return activeNetwork != null && activeNetwork.isConnected();
    }

    private class WarningListAdapter extends ArrayAdapter<String> {

        private final Activity context;
        private final String[] texts;
        private final String[] descs;

        public WarningListAdapter(Activity context, String[] texts, String[] descs) {
            super(context, R.layout.warning_list_item, texts);
            this.context = context;
            this.texts = texts;
            this.descs = descs;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View rowView= inflater.inflate(R.layout.warning_list_item, null, true);
            TextView txtTitle = (TextView) rowView.findViewById(R.id.warning_text_title);

            TextView txtDesc = (TextView) rowView.findViewById(R.id.warning_text_desc);
            txtTitle.setText(texts[position]);
            txtDesc.setText(descs[position]);
            return rowView;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            case PoiHandler.SELECT_POI_PHOTO:
                if(resultCode == RESULT_OK){
                    poiHandler.addImagePoi(data.getData());
                }
                break;
        }
    }

    @Override
    public void setTitle(CharSequence title){
        mTitle = title;
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) actionBar.setTitle(mTitle);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, GPS_MIN_TIME, GPS_MIN_DIST, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}