<?php

namespace CorpusParole\Http\Controllers\Api;

use Illuminate\Http\Request;

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

use Es;
use Log;

class GeoStatsController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $area = $request->input('area');

        $filterManager = new CorpusFilterManager();
        $filters = $filterManager->prepareFilters($request);
        unset($filters['location']);
        $qFilterParts = $filterManager->buildESFilters($filters);
        if(is_null($qFilterParts)) {
            $qFilterParts = [];
        }

        if(!is_null($area) && $area !== config('corpusparole.geonames_earth_geonamesid')) {
            $qFilterParts[] = [
                'term' => [
                    "geonames_hierarchy" => $area
                ]
            ];
        }

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

        $queryES = [
            'index' => config('elasticsearch.index'),
            'body' => [
                "size" => 0,
                "query" => $query,
                "aggs" => [
                    "geos" => [
                        "terms" => [
                            "size" => 2147483647,
                            "field" => "geonames_hierarchy"
                        ]
                    ]
                ]
            ]
        ];
        $esRes = Es::search($queryES);

        $geosats = [];

        foreach($esRes['aggregations']['geos']['buckets'] as $bucket) {
            $geosats[(string)($bucket['key'])] = $bucket['doc_count'];
        }

        return response()->json(['geostats' => $geosats ]);
    }
}
