package com.esri.samples.featurelayers.list_releated_features;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Alert;
import javafx.scene.control.ListView;
import javafx.scene.control.TitledPane;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.ArcGISFeature;
import com.esri.arcgisruntime.data.ArcGISFeatureTable;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.RelatedFeatureQueryResult;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.MapView;

public class ListRelatedFeaturesSample extends Application {

  private MapView mapView;

  @Override
  public void start(Stage stage) throws Exception {

    try {
      // create stack pane and application scene
      StackPane stackPane = new StackPane();
      Scene scene = new Scene(stackPane);

      // set title, size, and add scene to stage
      stage.setTitle("List Related Features Sample");
      stage.setWidth(800);
      stage.setHeight(700);
      stage.setScene(scene);
      stage.show();

      // create a tree view for displaying the related features according to their feature table
      Accordion accordion = new Accordion();
      accordion.setMaxSize(200, 300);

      // use the Alaska National Parks and Preserves Species web map
      ArcGISMap map = new ArcGISMap("https://arcgisruntime.maps.arcgis.com/home/item.html?id=dcc7466a91294c0ab8f7a094430ab437");

      // add the map to the map view
      mapView = new MapView();
      mapView.setMap(map);

      // wait until the map is done loading
      map.addDoneLoadingListener(() -> {
        // get the first feature layer for querying
        FeatureLayer featureLayer = (FeatureLayer) map.getOperationalLayers().get(0);

        mapView.setOnMouseClicked(event -> {
          // check for primary or secondary mouse click
          if (event.isStillSincePress() && event.getButton() == MouseButton.PRIMARY) {

            // create a point from where the user clicked
            Point2D point = new Point2D(event.getX(), event.getY());

            // convert to map coordinate
            Point mapPoint = mapView.screenToLocation(point);

            // identify the clicked features
            QueryParameters queryParameters = new QueryParameters();
            queryParameters.setGeometry(GeometryEngine.buffer(mapPoint, 10));
            final ListenableFuture<FeatureQueryResult> selectFeatureQuery = featureLayer.selectFeaturesAsync
                (queryParameters, FeatureLayer.SelectionMode.NEW);
            selectFeatureQuery.addDoneListener(() -> {

              try {
                FeatureQueryResult result = selectFeatureQuery.get();
                // get the first selected feature
                Iterator<Feature> iterator = result.iterator();
                if (iterator.hasNext()) {
                  ArcGISFeature selectedFeature = (ArcGISFeature) iterator.next();
                  // get the feature's feature table
                  ArcGISFeatureTable featureTable = selectedFeature.getFeatureTable();

                  // query related features
                  final ListenableFuture<List<RelatedFeatureQueryResult>> relatedFeatureQuery = featureTable
                      .queryRelatedFeaturesAsync(selectedFeature);
                  relatedFeatureQuery.addDoneListener(() -> {
                    try {
                      //clear previous results
                      accordion.getPanes().clear();
                      // add all related features (grouped) into tree view
                      List<RelatedFeatureQueryResult> results = relatedFeatureQuery.get();
                      Map<String, List<RelatedFeatureQueryResult>> groups = results.stream()
                          .collect(Collectors.groupingBy(r -> r.getRelatedTable().getTableName()));
                      groups.keySet().forEach(k -> {
                        // create node for the feature table
                        ListView<String> featureList = new ListView<>();
                        TitledPane tablePane = new TitledPane(k, featureList);
                        accordion.getPanes().add(tablePane);
                        // create sub nodes for the related features
                        groups.get(k).forEach(r -> {
                          // show the related feature with its display field value
                          ArcGISFeature feature = r.getFeature();
                          String displayFieldName = feature.getFeatureTable().getLayerInfo().getDisplayFieldName();
                          String displayFieldValue = feature.getAttributes().get(displayFieldName).toString();
                          featureList.getItems().add(displayFieldValue);
                        });
                      });

                    } catch (InterruptedException | ExecutionException e) {
                      Alert alert = new Alert(Alert.AlertType.ERROR, "Failed to get related features");
                      alert.show();
                    }
                  });
                }

              } catch (InterruptedException | ExecutionException e) {
                Alert alert = new Alert(Alert.AlertType.ERROR, "Failed to get identify the selected feature");
                alert.show();
              }
            });
          }
        });
      });

      // add the map view and tree view to stack pane
      stackPane.getChildren().addAll(mapView, accordion);
      StackPane.setAlignment(accordion, Pos.TOP_LEFT);

    } catch (Exception e) {
      // on any error, display the stack trace.
      e.printStackTrace();
    }
  }

  /**
   * Stops and releases all resources used in application.
   */
  @Override
  public void stop() throws Exception {

    if (mapView != null) {
      mapView.dispose();
    }
  }

  /**
   * Opens and runs application.
   *
   * @param args arguments passed to this application
   */
  public static void main(String[] args) {

    Application.launch(args);
  }

}

@@ -1755,21 +1755,27 @@
 create a
- tree
+n accordion
  view fo
@@ -4232,20 +4232,31 @@
 ) in
-to tree view
+ panes of the accordion
 %0A   
@@ -4623,19 +4623,21 @@
  create 
-nod
+a pan
 e for th
@@ -4643,32 +4643,61 @@
 he feature table
+ with a list for its features
 %0A               
@@ -4898,77 +4898,8 @@
 e);%0A
-                        // create sub nodes for the related features%0A
     
@@ -5029,16 +5029,28 @@
 ld value
+ in the list
 %0A       
@@ -6054,12 +6054,17 @@
 and 
-tree
+accordion
  vie

update comments