<?php

namespace CorpusParole\Http\Controllers\Api;

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

use Es;

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

        $filterManager = new CorpusFilterManager();
        $filters = $filterManager->prepareFilters($request);
        unset($filters['language']);
        $qFilterParts = $filterManager->buildESFilters($filters);
        $query = $filterManager->buildQuery($qFilterParts);

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

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

        $languages = [];

        foreach ($esRes['aggregations']['languages']['buckets'] as $b) {
            $languages[$b['key']] = $b['doc_count'];
        }

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

    }

}
