Integrate corpus statistics endpoint

Change-Id: I0f31c33d262727442a8e5f7843a81c905fe37c3d
diff --git a/lib/Kalamar.pm b/lib/Kalamar.pm
index 572f006..f5dd76e 100644
--- a/lib/Kalamar.pm
+++ b/lib/Kalamar.pm
@@ -174,9 +174,8 @@
   $r->get('/')->to('search#query')->name('index');
 
   # Collection route
-  # TODO: Probably rename to /corpus
-  $r->get('/collection')->to('Search#collections')->name('collections');
-  $r->get('/collection/:id')->to('Search#collection')->name('collection');
+  $r->get('/corpus')->to('Search#corpus_info')->name('corpus');
+  # $r->get('/collection/:id')->to('Search#corpus_info')->name('collection');
 
   # Documentation routes
   $r->get('/doc')->to('documentation#page', page => 'korap')->name('doc_start');
diff --git a/lib/Kalamar/API.pm b/lib/Kalamar/API.pm
index 735767a..60e04db 100644
--- a/lib/Kalamar/API.pm
+++ b/lib/Kalamar/API.pm
@@ -285,6 +285,55 @@
 };
 
 
+# Get corpus statistics
+sub statistics {
+  my $self = shift;
+  my $index = shift;
+
+  # Get controller
+  my $c = $index->controller;
+
+  # If there is a callback, do async
+  my $cb = pop if ref $_[-1] && ref $_[-1] eq 'CODE';
+
+  my %param = @_;
+
+  my $url = Mojo::URL->new($index->api);
+
+  # Use hash slice to create path
+  $url->path('statistics');
+
+  my %query;
+  $query{corpusQuery} = $param{cq};
+
+  # Add query
+  $url->query(\%query);
+
+  $c->stash('search._resource_cache' => $url->to_string);
+
+  $c->app->log->debug('Statistics info: ' . $url);
+
+  # non-blocking
+  if ($cb) {
+    $c->user->auth_request(
+      get =>
+        $url => sub {
+          my $tx = pop;
+          $self->_process_response('resource', $index, $tx);
+          weaken $index;
+          return $cb->($index);
+        });
+  }
+
+  # Statistics info blocking
+  else {
+    my $tx = $c->user->auth_request(get => $url);
+    return $self->_process_response('resource', $index, $tx);
+  };
+};
+
+
+
 # Get resource information
 sub resource {
   my $self = shift;
diff --git a/lib/Kalamar/Controller/Search.pm b/lib/Kalamar/Controller/Search.pm
index 933c7df..968402d 100644
--- a/lib/Kalamar/Controller/Search.pm
+++ b/lib/Kalamar/Controller/Search.pm
@@ -1,5 +1,6 @@
 package Kalamar::Controller::Search;
 use Mojo::Base 'Mojolicious::Controller';
+use Mojo::Util qw/deprecated/;
 
 
 # Query the KorAP backends and render a template
@@ -183,12 +184,32 @@
 
 
 # Get information about collections
-sub collections {
+sub corpus_info {
   my $c = shift;
+  my $v = $c->validation;
+
+  $v->optional('cq');
 
   # Async
   $c->render_later;
 
+  $c->search->statistics(
+    cq => $v->param('cq'),
+    sub {
+      my $notes = $c->notifications(json => $c->stash('search.resource'));
+      return $c->render(json => $notes);
+    }
+  );
+};
+
+
+sub collections {
+  my $c = shift;
+  # Async
+  $c->render_later;
+
+  deprecated 'collections() is deprecated in favour of corpus_info';
+
   # Get resource (for all)
   $c->search->resource(
     type => 'collection',