<?php

namespace Lc\ShopBundle\Twig;

use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Context\ReductionCartInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class BackendTwigExtension extends AbstractExtension
{
        public $em;
        public $trans;

        public function __construct(EntityManagerInterface $em, TranslatorInterface $translator)
        {
                $this->em = $em;
                $this->trans = $translator;

        }


        public function getFunctions()
        {
                return array(
                        new TwigFunction('list_reduction_codes', [$this, 'getListReductionCodes']),

                );
        }

        public function getFilters()
        {
                return [
                        new TwigFilter('lc_trad', [$this, 'lcTrad']),
                        new TwigFilter('uc_first', [$this, 'ucFirst'])

                ];
        }

        public function ucFirst($string)
        {
                return ucfirst($string);

        }

        public function lcTrad($field, $entityName, $type = "field")
        {
                if(strpos($field, '.')===false) {
                        $tradKey = $type . '.' . $entityName . '.' . $field;
                        $tradDefaultKey = $type . '.default.' . $field;
                }else{
                        $tradKey = $type . $field;
                        $tradDefaultKey = $type .'.default'. substr($field,strpos($field, '.'));
                }
                $trad = $this->trans->trans($tradKey, array(), 'lcshop');
                if ($trad == $tradKey) {
                        $trad = $this->trans->trans($tradDefaultKey, array(), 'lcshop');
                }
                return $trad;
        }

        public function getListReductionCodes()
        {
                $reductionCartRepo = $this->em->getRepository(ReductionCartInterface::class);
                $codesToReturn = array();
                foreach ($reductionCartRepo->getValuesOfFieldCode() as $codes) {
                        foreach ($codes['codes'] as $code) {
                                $codesToReturn[] = $code;
                        }
                }
                ;
                return $codesToReturn;

        }


}