<?php

namespace CorpusParole\Http\Controllers\Api;

use Illuminate\Http\Request;
use CorpusParole\Http\Requests;
use CorpusParole\Http\Controllers\Controller;
use CorpusParole\Services\LexvoResolverInterface;
use CorpusParole\Services\LexvoResolverException;

use CorpusParole\Libraries\Filters\CorpusFilterManager;
use CorpusParole\Libraries\Utils;

class LexvoController extends Controller
{
    public function __construct(LexvoResolverInterface $lexvoResolver) {
        $this->lexvoResolver = $lexvoResolver;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id od comma separatedlist of ids
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try {
            $ids = [];
            $corpusIds = [];
            foreach(explode(",", $id) as $idStr) {
                if(Utils::startsWith($idStr, config('corpusparole.language_corpus_node_prefix'))) {
                    $corpusIds[] = $idStr;
                } else {
                    $ids[] = $idStr;
                }
            }
            $lexvosNames = $this->lexvoResolver->getNames($ids);
            $filterManager = new CorpusFilterManager();
            $corpusNames = array_reduce($corpusIds, function($res,$cid) use ($filterManager) {
                $cNode = $filterManager->getLanguageNode($cid);
                if(is_null($cNode)) {
                    $res[$cid] = null;
                } else {
                    $res[$cid] = $cNode['name'];
                }
                return $res;
            }, []);
            return response()->json(['lexvoids' => array_merge($lexvosNames, $corpusNames)]);
        } catch (LexvoResolverException $e) {
            abort(500, $e->getMessage());
        }
    }

}
