<?php

namespace AppBundle\Menu\Admin;

use AppBundle\Enum\MediaType;
use AppBundle\Enum\ModuleType;
use AppBundle\Enum\OperationPEEState;
use AppBundle\Enum\TypeTemplateTitle;
use AppBundle\Helper\ModuleHelper;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\TranslatorInterface;
use AppBundle\Enum\UserType;

class MainBuilder
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var FactoryInterface
     */
    private $factory;

    /**
     * @var string
     */
    private $folderCloudUri;

    /**
     * @var mixed
     */
    private $route;

    /**
     * @var mixed
     */
    private $routeParams;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    public function __construct(
        string $folderCloudUri,
        EntityManagerInterface $em,
        FactoryInterface $factory,
        RequestStack $requestStack,
        TranslatorInterface $translator)
    {
        $request = $requestStack->getCurrentRequest();

        $this->em = $em;
        $this->factory = $factory;
        $this->folderCloudUri = $folderCloudUri;
        $this->translator = $translator;
        $this->route = $request->get('_route');
        $this->routeParams = $request->get('_route_params');
    }

    /**
     * @return ItemInterface
     */
    public function menu(): ItemInterface
    {
        $menu = $this->factory->createItem('root');
        $menu->setChildrenAttribute('class', 'nav');

        $this->addDashboard($menu);
        $this->addPage($menu);
        $this->addModule($menu);
        //$this->addSlider($menu);
        $this->addMedia($menu);
        $this->addArticle($menu);
        $this->addUser($menu);
        $this->addItdlc($menu);
        $this->addPee($menu);
        $this->addStatistics($menu);
        $this->addSettings($menu);

        return $menu;
    }

    
    /**
     * @param ItemInterface $menu
     */
    private function addDashboard(ItemInterface &$menu): void
    {
        $menu->addChild('dashboard', [
            'current' => 'admin_homepage' === $this->route,
            'label' => $this->translator->trans('menu.admin.dashboard.label', [], 'menu'),
            'route' => 'admin_homepage',
        ]);
    }


    /**
     * @param ItemInterface $menu
     */
    private function addPage(ItemInterface &$menu): void
    {
        $menu->addChild('pages', [
            'current' => 'admin_menu' === $this->route,
            'label' => $this->translator->trans('menu.admin.pages.label', [], 'menu'),
            'route' => 'admin_menu',
            'routeParameters' => [
                'menu_type' => 'main',
            ],
        ]);

        if ('admin_menu' === $this->route) {
            $menu['pages']->setCurrent(true);

            $menu['pages']->addChild('main', [
                'current' => 'main' === $this->routeParams['menu_type'],
                'label' => $this->translator->trans('menu.admin.pages.principal.label', [], 'menu'),
                'route' => 'admin_menu',
                'routeParameters' => [
                    'menu_type' => 'main',
                ],
            ]);

            $menu['pages']->addChild('sitemap', [
                'current' => 'sitemap' === $this->routeParams['menu_type'],
                'label' => $this->translator->trans('menu.admin.pages.pied.label', [], 'menu'),
                'route' => 'admin_menu',
                'routeParameters' => [
                    'menu_type' => 'sitemap',
                ],
            ]);

            $menu['pages']->addChild('hidden', [
                'current' => 'hidden' === $this->routeParams['menu_type'],
                'label' => $this->translator->trans('menu.admin.pages.virtuel.label', [], 'menu'),
                'route' => 'admin_menu',
                'routeParameters' => [
                    'menu_type' => 'hidden',
                ],
            ]);
        }
    }


    /**
     * @param ItemInterface $menu
     */
    private function addModule(ItemInterface &$menu): void
    {
        $menu->addChild('modules', [
            'label' => $this->translator->trans('menu.admin.modules.label', [], 'menu'),
            'route' => 'admin_module',
            'routeParameters' => [
                'type' => 'all',
                'page' => '1',
            ],
        ]);
        /* 
        if ('admin_module' === $this->route) {
            $menu['modules']->setCurrent(true);

            $menu['modules']->addChild('all', [
                'current' => 'all' === $this->routeParams['type'],
                'label' => $this->translator->trans('menu.module.all.label', [], 'menu'),
                'route' => 'admin_module',
                'routeParameters' => [
                    'type' => 'all',
                ],
            ]);

            $typeList = ModuleHelper::getTypeList();

            foreach ($typeList as $type) {
                $menu['modules']->addChild($type, [
                    'current' => $type === $this->routeParams['type'],
                    'label' => $this->translator->trans('word.module.'.$type, [], 'word'),
                    'route' => 'admin_module',
                    'routeParameters' => [
                        'type' => $type,
                    ],
                ]);
            }
        } 
        */
    }

    
    /**
     * @param ItemInterface $menu
     */
    private function addMedia(ItemInterface &$menu): void
    {
        $menu->addChild('medias', [
            'label' => $this->translator->trans('menu.admin.medias.label', [], 'menu'),
            'route' => 'admin_media',
            'routeParameters' => [
                'type' => 'all',
                'page' => '1',
            ],
        ]);
        if ('admin_media' === $this->route) {
            $menu['medias']->setCurrent(true);

            $menu['medias']->addChild('all', [
                'current' => 'all' === $this->routeParams['type'],
                'label' => 'Tous',
                'route' => 'admin_media',
                'routeParameters' => [
                    'type' => 'all',
                ],
            ]);

            $menu['medias']->addChild('pdf', [
                'current' => MediaType::PDF === $this->routeParams['type'],
                'label' => 'PDF',
                'route' => 'admin_media',
                'routeParameters' => [
                    'type' => MediaType::PDF,
                ],
            ]);

            $menu['medias']->addChild('pictures', [
                'current' => MediaType::PICTURE === $this->routeParams['type'],
                'label' => 'Images',
                'route' => 'admin_media',
                'routeParameters' => [
                    'type' => MediaType::PICTURE,
                ],
            ]);

            $menu['medias']->addChild('videos', [
                'current' => MediaType::VIDEO === $this->routeParams['type'],
                'label' => 'Vidéos',
                'route' => 'admin_media',
                'routeParameters' => [
                    'type' => MediaType::VIDEO,
                ],
            ]);
        }
    }

    /**
     * @param ItemInterface $menu
     */
    private function addArticle(ItemInterface &$menu): void
    {
        $menu->addChild('articles', [
            'label' => $this->translator->trans('menu.admin.articles.label', [], 'menu'),
            'route' => 'admin_actu',
            'routeParameters' => [
                'type' => 'all',
            ],
        ]);
        if ('admin_actu' === $this->route) {
            $menu['articles']->setCurrent(true);

            $qb = $this->em->createQueryBuilder();
            $qb->select('m')
                ->from('AppBundle:Menu', 'm')
                ->leftJoin('m.typeTemplate', 't')
                ->where('t.title = :t_title')
                ->orderBy('m.position', 'ASC')
                ->addOrderBy('m.id', 'ASC')
                ->setParameter('t_title', TypeTemplateTitle::NEWS);
            $categories = $qb->getQuery()->getResult();

            $menu['articles']->addChild('all', [
                'label' => 'Tous',
                'route' => 'admin_actu',
                'routeParameters' => [
                    'type' => 'all',
                ],
            ]);
            foreach ($categories as $categorie) {
                $categorie_id = $categorie->getId();

                $menu['articles']->addChild($categorie->getId(), [
                    'label' => $categorie->getTitle(),
                    'route' => 'admin_actu',
                    'routeParameters' => [
                        'type' => $categorie_id,
                    ],
                ]);
            }
        }
    }


    /**
     * @param ItemInterface $menu
     */
    private function addItdlc(ItemInterface &$menu): void
    {

        $menu->addChild('itdlc', [
            'current' => 'admin_demande_itdlc' === $this->route,
            'label' => $this->translator->transchoice('menu.admin.itdlc.label', 2, [], 'menu'),
            'route' => 'admin_demande_itdlc',
        ]);

        $menu['itdlc']->addChild('demandes', [
            'label' => $this->translator->transchoice('menu.admin.itdlc.demandes.label', 2, [], 'menu'),
            'route' => 'admin_demande_itdlc',
        ]);

        $menu['itdlc']->addChild('operations', [
            'current' => 'admin_operation_itdlc' === $this->route,
            'label' => $this->translator->transchoice('menu.admin.itdlc.operations.label', 2, [], 'menu'),
            'route' => 'admin_operation_itdlc',
        ]);

        $menu['itdlc']->addChild('historique_mer', [
            'current' => 'admin_mer_itdlc' === $this->route,
            'label' => $this->translator->transchoice('menu.admin.itdlc.historique.label', 2, [], 'menu'),
            'route' => 'admin_mer_itdlc',
        ]);

        
        if ('admin_demande_itdlc' === $this->route) {
            
            $menu['itdlc']['demandes']->setCurrent(true);
            

            $menu['itdlc']['demandes']->addChild('teachers', [
                'current' => UserType::TEACHER === $this->routeParams['user_type'],
                'label' => $this->translator->transchoice('form.teacher.label', 2, [], 'form'),
                'route' => 'admin_demande_itdlc',
                'routeParameters' => [
                    'user_type' => UserType::TEACHER,
                ],
            ]);

            $menu['itdlc']['demandes']->addChild('engineers', [
                'current' => UserType::ENGINEER === $this->routeParams['user_type'],
                'label' => $this->translator->transchoice('form.engineer.label', 2, [], 'form'),
                'route' => 'admin_demande_itdlc',
                'routeParameters' => [
                    'user_type' => UserType::ENGINEER,
                ],
            ]);

            $menu['itdlc']['demandes']->addChild('folder_cloud_uri', [
                'label' => 'Drive',
                'linkAttributes' => [
                    'class' => 'icon-google-drive',
                    'target' => '_blank',
                ],
                'uri' => $this->folderCloudUri,
            ]);
        }
      
    }


   

    /**
     * @param ItemInterface $menu
     */
    private function addPee(ItemInterface &$menu): void
    {
        $menu->addChild('pee', [
            'current' => 'admin_demande_pee_liste' === $this->route,
            'label' => $this->translator->transchoice('menu.admin.pee.label', 2, [], 'menu'),
            'route' => 'admin_demande_pee_liste',
        ]);
        
        $menu['pee']->addChild('demandes_pee', [
            'current' => 'admin_demande_pee_liste' === $this->route,
            'label' => $this->translator->transchoice('menu.admin.pee.demandes.label', 2, [], 'menu'),
            'route' => 'admin_demande_pee_liste',
        ]);

        $menu['pee']->addChild('operations_pee', [
            'current' => 'admin_operation_pee' === $this->route,
            'label' => $this->translator->transchoice('menu.admin.pee.operations.label', 2, [], 'menu'),
            'route' => 'admin_operation_pee',
            'routeParameters' => [
                'state' => OperationPEEState::OPEN,
            ],
        ]);
    }

    /**
     * @param ItemInterface $menu
     */
    private function addPeeOperation(ItemInterface &$menu): void
    {
        $menu->addChild('operations_pee', [
            'current' => 'admin_operation_pee' === $this->route,
            'label' => 'Opérations PEE',
            'route' => 'admin_operation_pee',
            'routeParameters' => [
                'state' => OperationPEEState::OPEN,
            ],
        ]);
    }

    /**
     * @param ItemInterface $menu
     */
    private function addSettings(ItemInterface &$menu): void
    {
        $menu->addChild('settings', [
            'current' => 'admin_settings' === $this->route || 'operationpee_category_index' === $this->route,
            'label' => $this->translator->trans('menu.admin.settings.label', [], 'menu'),
            'route' => 'operationpee_category_index',
        ]);

        if (in_array($this->route, ['operationpee_category_index', 'admin_sms_model_index', 'company_index', 'settings_operationitdlc', 'partner_index'])) {
            $menu['settings']->setCurrent(true);

            
            $menu['settings']->addChild('config', [
                'current' => 'admin_settings_config_index' === $this->route,
                'label' => $this->translator->transchoice('menu.admin.settings.config.label', 2, [], 'menu'),
                'route' => 'admin_settings_config_index'
            ]);

            $menu['settings']->addChild('operationpee-category', [
                'current' => 'operationpee_category_index' === $this->route,
                'label' => $this->translator->transchoice('menu.admin.settings.categoriePee.label', 2, [], 'menu'),
                'route' => 'operationpee_category_index'
            ]);
            $menu['settings']->addChild('sms-model', [
                'current' => 'admin_sms_model_index' === $this->route,
                'label' => $this->translator->transchoice('form.sms.model.label', 2, [], 'form'),
                'route' => 'admin_sms_model_index'
            ]);
            $menu['settings']->addChild('companies', [
                'current' => 'company_index' === $this->route,
                'label' => $this->translator->transchoice('form.company.label', 2, [], 'form'),
                'route' => 'company_index'
            ]);
            
            /*
            $menu['settings']->addChild('operation_itdlc', [
                'current' => 'settings_operationitdlc' === $this->route,
                'label' => $this->translator->transchoice('form.itdlc.operation.label', 2, [], 'form'),
                'route' => 'settings_operationitdlc'
            ]);
            */
            $menu['settings']->addChild('partners', [
                'current' => 'partner_index' === $this->route,
                'label' => $this->translator->transchoice('form.partner.label', 2, [], 'form'),
                'route' => 'partner_index'
            ]);
        }
    }

    
    /**
     * @param ItemInterface $menu
     */
    private function addSlider(ItemInterface &$menu): void
    {
        $menu->addChild('sliders', [
            'current' => 'admin_slider' === $this->route,
            'label' => 'Sliders',
            'route' => 'admin_slider',
        ]);
    }

    /**
     * @param ItemInterface $menu
     */
    private function addStatistics(ItemInterface &$menu): void
    {
        $menu->addChild('statistiques', [
            'label' => 'Statistiques',
            'route' => 'admin_statistics_user',
        ]);
        if (in_array($this->route, ['admin_statistics_user', 'admin_statistics_itdlc_operation', 'admin_statistics_pee_demande', 'admin_statistics_pee_operation', 'admin_testimonial','admin_testimonial_edit', 'admin_testimonial_edit', 'admin_contact', 'admin_contact_view'])) {
            $menu['statistiques']->setCurrent(true);

            $menu['statistiques']->addChild('teachers', [
                'label' => $this->translator->transchoice('form.teacher.label', 2, [], 'form'),
                'route' => 'admin_statistics_user',
                'routeParameters' => [
                    'type' => UserType::TEACHER,
                ],
            ]);
            if ('admin_statistics_user' === $this->route && array_key_exists('type', $this->routeParams) && UserType::TEACHER === $this->routeParams['type']) {
                $menu['statistiques']['teachers']->setCurrent(true);
            }

            $menu['statistiques']->addChild('engineers', [
                'label' => $this->translator->transchoice('form.engineer.label', 2, [], 'form'),
                'route' => 'admin_statistics_user',
                'routeParameters' => [
                    'type' => UserType::ENGINEER,
                ],
            ]);
            if ('admin_statistics_user' === $this->route && array_key_exists('type', $this->routeParams) && UserType::ENGINEER === $this->routeParams['type']) {
                $menu['statistiques']['engineers']->setCurrent(true);
            }

            $menu['statistiques']->addChild('operations_itdlc', [
                'current' => 'admin_statistics_itdlc_operation' === $this->route,
                'label' => 'Opérations ITDLC',
                'route' => 'admin_statistics_itdlc_operation',
            ]);

            $menu['statistiques']->addChild('demandes_pee', [
                'current' => 'admin_statistics_pee_demande' === $this->route,
                'label' => 'Demandes PEE',
                'route' => 'admin_statistics_pee_demande',
            ]);

            $menu['statistiques']->addChild('operations_pee', [
                'current' => 'admin_statistics_pee_operation' === $this->route,
                'label' => 'Opérations PEE',
                'route' => 'admin_statistics_pee_operation',
            ]);

            $menu['statistiques']->addChild('testimonials', [
                'label' => $this->translator->trans('menu.testimonial.main.label', [], 'menu'),
                'route' => 'admin_testimonial',
                'routeParameters' => [
                    'page' => '1',
                ],
            ]);

            if ('admin_testimonial_add' === $this->route || 'admin_testimonial_edit' === $this->route) {
                $menu['statistiques']['testimonials']->setCurrent(true);
            }

            $menu['statistiques']->addChild('contact_form_data', [
                'label' => $this->translator->trans('menu.contact_form_data.main.label', [], 'menu'),
                'route' => 'admin_contact',
                'routeParameters' => [
                    'page' => '1',
                ],
            ]);

            if ('admin_contact_view' === $this->route) {
                $menu['statistiques']['contact_form_data']->setCurrent(true);
            }
        }
    }

    /**
     * @param ItemInterface $menu
     */
    private function addUser(ItemInterface &$menu): void
    {
        $menu->addChild('communaute', [
            'label' => 'Communauté',
            'route' => 'admin_list_user',
            'routeParameters' => [
                'type' => 'all',
            ],
        ]);
        if ('admin_list_user' === $this->route) {
            $menu['communaute']->setCurrent(true);

            // Types d'utilisateurs et leur nombre pour chaque.
            // Seulement pour les utilisateurs dont le type a une longueur de caractères supérieure à 1.
            $qb = $this->em->createQueryBuilder();
            $qb->select('u.type, COUNT(u) AS nb')
                ->from('AppBundle:User', 'u')
                ->where($qb->expr()->gt(
                    $qb->expr()->length('u.type'),
                    ':u_type_length_mini'
                ))
                ->groupBy('u.type')
                ->setParameter('u_type_length_mini', 1)
            ;
            $users = $qb->getQuery()->getArrayResult();

            // Key: user type ; value: user number
            $usersQty = array_column($users, 'nb', 'type');

            $menu['communaute']->addChild('tous', [
                'current' => 'all' === $this->routeParams['type'],
                'label' => sprintf('Tous (%s)', array_sum($usersQty)),
                'route' => 'admin_list_user',
                'routeParameters' => [
                    'type' => 'all',
                ],
            ]);

            foreach ($usersQty as $type => $qty) {
                $menu['communaute']->addChild($type . 's', [
                    'current' => $type === $this->routeParams['type'],
                    'label' => sprintf(
                        '%s (%s)',
                        $this->translator->transchoice('form.' . $type . '.label', $qty, [], 'form'),
                        $qty
                    ),
                    'route' => 'admin_list_user',
                    'routeParameters' => [
                        'type' => $type,
                    ],
                ]);
            }
        }
    }
}
