<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Repository\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

class CuveeController extends AbstractController
{
    private $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    /**
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction(Request $request)
    {
        $cuvees    = $this->productRepository->findOnlyCuvee();
        $names     = [];
        $refCuvees = [];

        /** @var Product $cuvee */
        foreach ($cuvees as $key => $cuvee) {
            if (in_array($cuvee->getName(), $names)) {
                $prevCuvee = $refCuvees[$cuvee->getName()];
                $cuvee->translate($request->getLocale())->setQuality($prevCuvee['quality'].' & '.$cuvee->getQuality());
                unset($cuvees[$prevCuvee['key']]);
            } else {
                array_push($names, $cuvee->getName());
                $refCuvees[$cuvee->getName()] =
                    [
                        'key'     => $key,
                        'quality' => $cuvee->getQuality(),
                    ];
            }
        }

        return $this->render(
            'cuvees.html.twig',
            [
                'classMenu' => 'black',
                'subMenu'   => true,
                'cuvees'    => $cuvees,
            ]
        );
    }

    /**
     * @param Product $product
     *
     * @Route({
     *     "fr": "/les-cuvees/{slug}",
     *     "en": "/en/les-cuvees/{slug}"
     * }, name="cuveeItem")
     * @ParamConverter("product", converter="translation_converter")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function itemAction(Product $product)
    {
        $cuvees = $this->productRepository->findOnlyCuvee();
        $prevProduct = $this->productRepository->findPreviousCuvee($product->getPosition());
        $nextProduct = $this->productRepository->findNextCuvee($product->getPosition());

        return $this->render(
            'cuveeItem.html.twig',
            [
                'cuvees' => $cuvees,
                'item'   => $product,
                'prevItem' => $prevProduct,
                'nextItem' => $nextProduct,
            ]
        );
    }
}
