<?php

namespace App\Controller;

use App\Enum\CurrencyEnum;
use App\Utils\OperationUtils;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class OperationsController extends AbstractController
{
    protected $em;
    protected $paginator;
    protected $operationUtils;

    public function __construct(EntityManagerInterface $em, PaginatorInterface $paginator, OperationUtils $operationUtils)
    {
        $this->em = $em;
        $this->paginator = $paginator;
        $this->operationUtils = $operationUtils;
    }

    /**
     * @Route("/show/operations/{currency}", name="show_operations", defaults={"currency": "emlc"})
     */
    public function showOperationsAction(Request $request, $currency = CurrencyEnum::CURRENCY_MLC)
    {
        if (empty($this->getUser())) {
            return $this->redirectToRoute('index');
        }
        if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
            throw new \Exception('Opération impossible ! Type de currency  ' . $currency . ' inexistant');
        }

        $query = $this->operationUtils->getUserOperationsByCurrency($currency);
        $operations = [];
        if (null !== $query) {
            $operations = $this->paginator->paginate(
                $query, /* query NOT result */
                $request->query->getInt('page', 1)/*page number*/,
                20/*limit per page*/
            );
            $operations->setCustomParameters([
                'align' => 'center',
            ]);
        }

        return $this->render('@kohinos/flux/operations.html.twig', [
            'operations' => $operations,
            'currency' => $currency,
        ]);
    }
}
