package de.c3nav.droid;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import de.c3nav.droid.BuildConfig;
import de.c3nav.droid.R;

public class MainActivity extends AppCompatActivity {

    private WifiManager wifiManager;
    private WifiReceiver wifiReceiver;
    private WebView webView;
    private MobileClient mobileClient;
    private boolean canWifiTimestamp;

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

        canWifiTimestamp = android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;

        final View pView = LayoutInflater.from(this).inflate(R.layout.progressbar, null);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(pView);
        getSupportActionBar().getCustomView().setVisibility(View.GONE);

        mobileClient = new MobileClient();

        webView = (WebView) findViewById(R.id.webView);

        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUserAgentString("c3navClient/Android/" + BuildConfig.VERSION_CODE);
        webView.addJavascriptInterface(mobileClient, "mobileclient");

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView v, int progress) {
                if (progress < 100 && pView.getVisibility() == View.GONE) {
                    pView.setVisibility(View.VISIBLE);
                }
                if (progress == 100) {
                    pView.setVisibility(View.GONE);
                }
            }

        });

        String url_to_call = BuildConfig.WEB_URL;
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data != null) {
            Uri.Builder tmp_uri = data.buildUpon();
            tmp_uri.scheme("https");
            url_to_call = tmp_uri.build().toString();
        }

        webView.loadUrl(url_to_call);

        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiReceiver = new WifiReceiver();
        registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        wifiManager.startScan();
    }

    class MobileClient {
        private JSONArray nearbyStations;

        @JavascriptInterface
        public String getNearbyStations() { return this.nearbyStations.toString(); }

        public void setNearbyStations(JSONArray nearbyStations) {
            this.nearbyStations = nearbyStations;
        }

        @JavascriptInterface
        public void scanNow() {
            wifiManager.startScan();
        }
    }

    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    List<ScanResult> wifiList = wifiManager.getScanResults();
                    JSONArray ja = new JSONArray();
                    for(ScanResult result : wifiList) {
                        JSONObject jo = new JSONObject();
                        try {
                            jo.put("bssid", result.BSSID);
                            jo.put("ssid", result.SSID);
                            jo.put("level", result.level);

                            if (canWifiTimestamp) {
                                if (SystemClock.elapsedRealtime()-result.timestamp/1000 > 1000) {
                                    continue;
                                }
                                jo.put("last", SystemClock.elapsedRealtime()-result.timestamp/1000);
                            }
                            ja.put(jo);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    mobileClient.setNearbyStations(ja);
                    webView.loadUrl("javascript:nearby_stations_available();");
                }
            });
        }
    }
}

@@ -282,16 +282,42 @@
 .Build;%0A
+import android.os.Bundle;%0A
 import a
@@ -392,34 +392,8 @@
 ty;%0A
-import android.os.Bundle;%0A
 impo
@@ -672,73 +672,60 @@
 til.
-List;%0A%0Aimport de.c3nav.droid.BuildConfig;%0Aimport de.c3nav.droid.R
+HashMap;%0Aimport java.util.List;%0Aimport java.util.Map
 ;%0A%0Ap
@@ -938,32 +938,61 @@
 ate 
-boolean canWifiTimestamp
+Map%3CString, Integer%3E lastLevelValue = new HashMap%3C%3E()
 ;%0A%0A 
@@ -1158,108 +1158,8 @@
 );%0A%0A
-        canWifiTimestamp = android.os.Build.VERSION.SDK_INT %3E= Build.VERSION_CODES.JELLY_BEAN_MR1;%0A%0A
     
@@ -3087,16 +3087,28 @@
 ions() %7B
+%0A           
  return 
@@ -3138,16 +3138,24 @@
 tring();
+%0A       
  %7D%0A%0A    
@@ -3758,16 +3758,17 @@
      for
+ 
 (ScanRes
@@ -4092,24 +4092,67 @@
 if (
-canWifiTimestamp
+Build.VERSION.SDK_INT %3E= Build.VERSION_CODES.JELLY_BEAN_MR1
 ) %7B%0A
@@ -4208,33 +4208,35 @@
 lapsedRealtime()
--
+ - 
 result.timestamp
@@ -4231,25 +4231,27 @@
 lt.timestamp
-/
+ / 
 1000 %3E 1000)
@@ -4409,17 +4409,19 @@
 altime()
--
+ - 
 result.t
@@ -4428,17 +4428,19 @@
 imestamp
-/
+ / 
 1000);%0A 

Replace canWifiTimestamp by direct if for better tooling support