<?php

namespace KupShop\ElninoBundle\View;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\CatalogBundle\View\AutocompleteView;
use KupShop\ElninoBundle\Util\ElninoMultiFetch;

class ElninoAutocompleteView extends AutocompleteView
{
    protected function processSections(array $sphinxResult)
    {
        foreach ($sphinxResult as &$section) {
            $section['label'] = $section['path'];
        }

        $sectionIDs = array_map(function ($val) {
            return $val['id'];
        }, $sphinxResult);
        $qb = sqlQueryBuilder()->select('id, plural')->from('sections')
            ->where(\Query\Operator::inIntArray($sectionIDs, 'id'))
            ->execute();
        $plurals = [];
        foreach ($qb as $row) {
            $plurals[$row['id']] = $row['plural'];
            foreach ($sphinxResult as &$section) {
                if ($section['id'] == $row['id']) {
                    $section['name'] = !empty($plurals[$section['id']]) ? $plurals[$section['id']] : $section['name'];
                    continue 2;
                }
            }
        }

        return array_values($sphinxResult);
    }

    protected function getProductList(): \ProductList
    {
        $productList = parent::getProductList();

        $productList->addResultModifiers(function (ProductCollection $productCollection) {
            ElninoMultiFetch::fetchAdditionalData($productCollection);
        });

        return $productList;
    }

    protected function getProductResult(\Product $product): array
    {
        $data = parent::getProductResult($product);

        $data['model_short_title'] = $product->model_short_title ?? '';
        $data['model_section'] = $product->model_section ?? '';

        return $data;
    }
}
