<?php

namespace CorpusParole\Http\Controllers\Api;

use CorpusParole\Http\Controllers\Controller;
use CorpusParole\Libraries\Filters\CorpusFilterManager;

use Illuminate\Http\Request;

use Es;

class DiscourseController extends Controller
{

    /**
     * Display the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $filterManager = new CorpusFilterManager();
        $filters = $filterManager->prepareFilters($request);
        //unset($filters['discourses']);
        $qFilterParts = $filterManager->buildESFilters($filters);

        $query = $filterManager->buildQuery($qFilterParts);



        $esQuery = [
            'index' => config('elasticsearch.index'),
            'body' => [
                "size" => 0,
                "query" => $query,
                "aggs" => [
                    "discourses" => [
                        "terms" => [ "field" => "discourse_types", "order" => [ "_count" => "desc" ], "size" => 2147483647 ]
                    ]
                ]
            ]
        ];

        $esRes = Es::search($esQuery);

        $discourses = [];

        foreach ($esRes['aggregations']['discourses']['buckets'] as $b) {
            $key = $b['key'];
            $count = $b['doc_count'];
            $label = config('corpusparole.corpus_discourse_type')[$key];
            $discourses[$key] = [
                "label" => $label,
                "count" => $count
            ];
        }

        return response()->json(['discourses' => $discourses ]);

    }

}
