<?php

namespace CorpusParole\Http\Controllers\Api;

use CorpusParole\Http\Controllers\Controller;

use Illuminate\Http\Request;
use EasyRdf\Resource;
use EasyRdf\Literal;

use Es;
use Log;

use CorpusParole\Services\LexvoResolverInterface;
use CorpusParole\Services\BnfResolverInterface;
use CorpusParole\Libraries\Filters\CorpusFilterManager;


class ThemeController extends Controller
{
    public function __construct(LexvoResolverInterface $lexvoResolver, BnfResolverInterface $bnfResolver) {
        $this->lexvoResolver = $lexvoResolver;
        $this->bnfResolver = $bnfResolver;
    }

    /**
     * Display the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $filter = $request->input('filter', 'bnf');
        $index = $request->input('index', 0);
        $limit = $request->input('limit', config('corpusparole.theme_default_limit'));
        $sort = $request->input('sort', 'count');

        if($filter === 'bnf') {
            $include = ".*\\|bnf\\|.*";
        }
        elseif($filter === 'lexvo') {
            $include = ".*\\|lxv\\|.*";
        }
        elseif($filter === 'olac') {
            $include = ".*\\|olac\\|.*";
        }
        elseif($filter === 'txt') {
            $include = ".*\\|txt\\|.*";
        }
        elseif($filter === 'all') {
            $include = false;
        }
        else {
            abort(401,"Value for filter parameter must be in 'bnf', 'lexvo', 'olac', 'txt', 'all'");
        }

        if($sort == "count" || $sort == "descending") {
            $order_field = "_count";
            $order_dir = "desc";
        } elseif($sort == "-count") {
            $order_field = "_count";
            $order_dir = "asc";
        } elseif ($sort == "label" || $sort == "alphabetical") {
            $order_field = "_term";
            $order_dir = "asc";
        } elseif ($sort == "-label") {
            $order_field = "_term";
            $order_dir = "desc";
        } else {
            $order_field = "_count";
            $order_dir = "desc";
        }

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

        $termSize = $limit * ($index+1);
        $esQuery = [
            'index' => config('elasticsearch.index'),
            'body' => [
                'size' => 0,
                'query' => $query,
                'aggs' => [
                    "subjects" => [
                        "nested" => [ "path" => "subject" ],
                        "aggs" => [
                            "subjects" => [
                                "terms" => [
                                    "field" => "subject.label_code",
                                    "size" => ($termSize==0)?2147483647:$termSize,
                                    "order" => [ $order_field => $order_dir ]
                                ]
                            ],
                            "subjects_count" => [
                                "cardinality" => [
                                    "field" => "subject.label_code"
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ];

        if($include) {
            $esQuery['body']['aggs']['subjects']['aggs']['subjects']['terms']['include'] = $include;
        }

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

        $themes = [];

        $bucketList = $esRes['aggregations']['subjects']['subjects']['buckets'];
        if($limit > 0) {
            $bucketList = array_slice($bucketList, $index*$limit, $limit);
        }

        foreach($bucketList as $bucket) {
            $parts = explode("|", $bucket['key']);
            $label = $parts[0];
            if($parts[1] === 'bnf' || $parts[1] === 'lxv') {
                $url = ['bnf' => config('corpusparole.bnf_ark_base_url'), 'lxv' => config('corpusparole.lexvo_base_url')][$parts[1]].$parts[2];
            }
            else {
                $url = $parts[2];
            }
            $themes[$url] = [
                "label" => $label,
                "count" => $bucket['doc_count']
            ];
        }

        return response()->json(['themes' => $themes, 'meta' => [ 'total' => $esRes['aggregations']['subjects']['subjects_count']['value']] ]);

    }

}
