<?php

namespace AppBundle\Controller\Module;

use AppBundle\Controller\ModuleController;
use AppBundle\Entity\Menu;
use AppBundle\Entity\Module;
use AppBundle\Entity\Company;
use AppBundle\Entity\Establishment;
use AppBundle\Entity\Partner;
use AppBundle\Enum\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class PartnersListController extends ModuleController
{
    /**
     * @param Int $moduleId Défini le module à afficher
     * @param string $force_layout Définit le type de rendu Twig souhaité
     * @param Int $menuId Défini le menu associé, la page actuelle qui demande l'affichage
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function renderModule(Int $moduleId, string $force_layout = null, Int $menuId = null)
    {
        $module = $this->em->getRepository(Module::class)->findOneBy([
            'isActive' => true, 
            'id' => $moduleId
        ]);
        
        if (empty($module)) {
            return new Response('');
        }

        //Force layout
        if (!empty($force_layout)) {
            $module->setLayout($force_layout);
        }
        
        $module->setFormClass($module->getType());
        $layout = $module->getLayoutPath();

        //Check if layout is correct
        if (!empty($force_layout) && strpos($layout, $force_layout) === false) {
            return new Response('');
        }

        //Custom request here
        //Mode Featured
        $listIds = (array) $module->getParams()->items;
        $partners = $this->em->getRepository(Partner::class)->findBy([
            'id' => $listIds
        ], 
        ['position' => 'ASC', 'name' => 'ASC', 'id' => 'ASC']
        //, (int) $module->getParams()->nb_items
        );

        if (empty($partners)) {
            return new Response('');
        }

        shuffle($partners); // Random ordering
        $partners = array_slice($partners, 0, (int) $module->getParams()->nb_items);// Slice

        // Specific to layout cols.html.twig
        switch ( count($partners) ) {
            case 1 :
            case 2 :
            case 3 :
                    $itemClass = "col-md-6 col-lg-4";
                    break;
            case 4 : 
            default:
                    $itemClass = "col-md-6 col-lg-3";
                    break;
        }

        $menuList = $this->em->getRepository(Menu::class)->findOneBy([
                'typeTemplate' => 11, 
        ]);

        return $this->render($layout , array(
            'module' => $module, 
            'menu' => $menuList,
            'partners' => $partners,
            'itemcol' => $itemClass,
        ));
    }
}
