/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.gnd.persistence.geojson;

import static com.google.android.gnd.util.ImmutableListCollector.toImmutableList;
import static java8.util.J8Arrays.stream;

import android.util.Log;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gnd.model.basemap.tile.Tile;
import com.google.android.gnd.model.basemap.tile.Tile.State;
import com.google.android.gnd.persistence.uuid.OfflineUuidGenerator;
import com.google.common.collect.ImmutableList;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.inject.Inject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GeoJsonParser {

  private static final String TAG = GeoJsonParser.class.getSimpleName();
  private final OfflineUuidGenerator uuidGenerator;

  @Inject
  GeoJsonParser(OfflineUuidGenerator uuidGenerator) {
    this.uuidGenerator = uuidGenerator;
  }

  private String readJsonFile(File file) {
    try {
      InputStream is = new FileInputStream(file);
      BufferedReader buf = new BufferedReader(new InputStreamReader(is));
      StringBuilder sb = new StringBuilder();

      int res = buf.read();
      while (res != -1) {
        sb.append(res);
        res = buf.read();
      }
      return sb.toString();
    } catch (IOException e) {
      Log.e(TAG, "Unable to load JSON", e);
    }
    return "";
  }

  /**
   * Returns the immutable list of tiles specified in {@param geojson} that intersect {@param
   * bounds}.
   */
  public ImmutableList<Tile> intersectingTiles(LatLngBounds bounds, File file) {
    String fileContents = readJsonFile(file);
    try {
      JSONObject geoJson = new JSONObject(fileContents);
      JSONArray features = geoJson.getJSONArray("features");

      return stream(toArray(features))
          .map(GeoJsonTile::new)
          .filter(tile -> tile.boundsIntersect(bounds))
          .map(this::jsonToTile)
          .collect(toImmutableList());

    } catch (JSONException e) {
      Log.e(TAG, "Unable to parse JSON", e);
    }

    return ImmutableList.of();
  }

  /**
   * Converts a JSONArray to an array of JSONObjects. Provided for compatibility with java8 streams.
   * JSONArray itself only inherits from Object, and is not convertible to a stream.
   */
  private static JSONObject[] toArray(JSONArray arr) {
    JSONObject[] result = new JSONObject[arr.length()];

    for (int i = 0; i < arr.length(); i++) {
      try {
        JSONObject o = arr.getJSONObject(i);
        result[i] = o;
      } catch (JSONException e) {
        Log.e(TAG, "couldn't parse json", e);
      }
    }

    return result;
  }

  /** Returns the {@link Tile} specified by {@param json}. */
  private Tile jsonToTile(GeoJsonTile json) {
    return Tile.newBuilder()
        .setId(uuidGenerator.generateUuid())
        .setUrl(json.getUrl().orElse(""))
        .setState(State.PENDING)
        .setPath(Tile.pathFromId(json.getId().orElse("")))
        .build();
  }
}

@@ -1670,24 +1670,43 @@
 e(File file)
+ throws IOException
  %7B%0A    try %7B
@@ -2099,24 +2099,24 @@
     
-%7D%0A    return %22%22;
+  throw e;%0A    %7D
 %0A  %7D
@@ -2314,24 +2314,36 @@
 ile file) %7B%0A
+    try %7B%0A  
     String f
@@ -2376,26 +2376,16 @@
 (file);%0A
-    try %7B%0A
       JS
@@ -2715,32 +2715,46 @@
  (JSONException 
+%7C IOException 
 e) %7B%0A      Log.e
@@ -3209,20 +3209,17 @@
     
-JSONObject o
+result%5Bi%5D
  = a
@@ -3243,31 +3243,8 @@
 i);%0A
-        result%5Bi%5D = o;%0A
     
@@ -3462,24 +3462,162 @@
 ile json) %7B%0A
+    // TODO: Instead of returning tiles with invalid state (empty URL/ID values)%0A    // Throw an exception here and handle it downstream.%0A
     return T

Improve code quality in GeoJsonParser