<?php

namespace Comitium5\DesignerBundle\Factory\Search\Result;

use Comitium5\DesignerBundle\ValueObjects\GroupByCollection;
use Comitium5\DesignerBundle\ValueObjects\GroupByObject;
use Comitium5\DesignerBundle\ValueObjects\SearchResultObject;

/**
 * Class ElasticSearchResultFactory
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Factory\Search\Result
 */
class ElasticSearchResultFactory
{
    /**
     * @param array $results
     *
     * @return SearchResultObject
     */
    public static function create(array $results): SearchResultObject
    {
        return new SearchResultObject(
            $results["results"],
            $results["page"],
            $results["total"],
            $results["totalPages"],
            $results["limit"],
            self::resolveOrderByCollection($results)
        );
    }

    /**
     * @param array $results
     *
     * @return GroupByCollection|null
     */
    private static function resolveOrderByCollection(array $results): ?GroupByCollection
    {
        if (empty($results['_aggregations']['types']['buckets'])) {
            return null;
        }

        $groupByCollection = new GroupByCollection();

        foreach ($results['_aggregations']['types']['buckets'] as $result) {
            $groupByCollection->add(
                new GroupByObject(
                    $result['key'],
                    $result['doc_count']
                )
            );
        }

        return $groupByCollection;
    }
}
