// This module defines the Angular controller that renders the Chord Diagram.
define(function(require) {

  // Load D3 v4 via our custom bundle build output.
  var d3 = require("../d3/d3.min");

  // Load the module that defines the Chord Diagram using D3.
  var ChordDiagram = require("./chordDiagram");

  // Load the module that defines the HTML Table using D3.
  var Table = require("./table");

  // Access the Kibana plugin Angular module.
  var module = require("ui/modules").get("kibana-chord");


  // Register the controller with the Kibana plugin Angular module.
  module.controller("ChordController", function($scope, $rootScope, Private, $element, $http) {

    // Access the DOM element provided by Angular's dependency injection.
    var div = $element[0];

    // Construct a Bootstrap Grid to position the Chord Diagram and Table.
    var container = d3.select(div)
            .style("width", "100%")
          .append("div")
            .attr("class", "container-fluid")
          .append("div")
            .attr("class", "row"),
        chordContainer = container
          .append("div")
            .attr("class", "col-md-6")
            .node(),
        tableContainer = container
          .append("div")
            .attr("class", "col-md-6")
            .node();


    // Construct an instance of the Chord Diagram.
    var chordDiagram = ChordDiagram(chordContainer);

    // Construct an instance of the HTML Table.
    var table = Table(tableContainer);

    // Metadata for rendering the HTML table.
    var columns = [
      { title: "Chord Weight", property: "1" },
      { title: "Chord Sources", property: "2" },
      { title: "Chord Destinations", property: "3" }
    ];

    // Converts hierarchical result set from ElasticSearch into a tabular form.
    // Returns an array of row objects, similar to the format returned by d3.csv.
    function tabify(response){
      var tabifyAggResponse = Private(require("ui/agg_response/tabify/tabify"));
      var tabified = tabifyAggResponse($scope.vis, response, { asAggConfigResults: true });

      return tabified.tables[0].rows.map(function (array){
        var row = {};
        array.forEach(function (entry){
          row[entry.aggConfig.id] = entry.value;
        });
        return row;
      });
    }

    // Update the visualization with new data as the query response changes.
    $scope.$watch("esResponse", function(response) {

      // Tabify the response.
      var data = tabify(response);

      // Render the Chord Diagram.
      chordDiagram(data);

      // Render the HTML Table.
      table(data, columns);
    });

    // Invoke our custom middleware for querying ElasticSearch
    // when the user clicks on the ribbon.
    //
    // The argument `options` has `source` and `destination` properties
    // based on which ribbon was clicked.
    chordDiagram.onRibbonClick(function (options){

      // Add index and time to the options,
      // which will be the HTTP POST payload.
      options.index = $scope.vis.indexPattern.id;
      options.time = $rootScope.timefilter.time;

      $http
        .post("/api/kibana-chord", options)
        .then(function successCallback(response){

          // TODO set the content of the table here.
          // table(tabify(response), columns);

          console.log(JSON.stringify(response.data));
        }, function errorCallback(response){
          throw response;
        });
    });
  });
});

@@ -1482,232 +1482,8 @@
 );%0A%0A
-    // Metadata for rendering the HTML table.%0A    var columns = %5B%0A      %7B title: %22Chord Weight%22, property: %221%22 %7D,%0A      %7B title: %22Chord Sources%22, property: %222%22 %7D,%0A      %7B title: %22Chord Destinations%22, property: %223%22 %7D%0A    %5D;%0A%0A
     
@@ -2373,26 +2373,185 @@
 e(data, 
-columns
+%5B%0A        %7B title: %22Chord Weight%22, property: %221%22 %7D,%0A        %7B title: %22Chord Sources%22, property: %222%22 %7D,%0A        %7B title: %22Chord Destinations%22, property: %223%22 %7D%0A      %5D
 );%0A
+%0A
     %7D);%0A
@@ -3141,99 +3141,283 @@
     
-// TODO set the content of the table here.%0A          // table(tabify(response), columns
+var data = response.data.hits.hits.map(function (d)%7B%0A            return %7B%0A              sourceip: d._source.sourceip,%0A              destinationip: d._source.destinationip,%0A              type: d._source.type%0A            %7D;%0A          %7D);%0A%0A          console.log(response.data
 );%0A
-%0A
     
@@ -3438,40 +3438,265 @@
 log(
-JSON.stringify(response.data)
+data);%0A%0A          // Render the HTML Table.%0A          table(data, %5B%0A            %7B title: %22Source IP%22, property: %22sourceip%22 %7D,%0A            %7B title: %22Destination IP%22, property: %22destinationip%22 %7D,%0A            %7B title: %22Type%22, property: %22type%22 %7D%0A          %5D
 );%0A
+%0A
     

Add 3 fields from query result to table