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

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Manager\SocialNetworkProviderManager;
use CpCreation\VitiCore\Library\Repository\LibraryRepository;
use CpCreation\VitiCore\SocialNetwork\Model\SocialNetwork;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkNewRepository;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class LibraryController extends AbstractController
{
    private $libraryRepository;
    private $socialNetworkRepository;
    private $socialNetworkNewRepository;
    private $socialNetworkProviderManager;

    public function __construct(LibraryRepository $libraryRepository,
        SocialNetworkRepository $socialNetworkRepository,
        SocialNetworkNewRepository $socialNetworkNewRepository,
        SocialNetworkProviderManager $socialNetworkProviderManager
    ) {
        $this->libraryRepository           = $libraryRepository;
        $this->socialNetworkRepository     = $socialNetworkRepository;
        $this->socialNetworkNewRepository   = $socialNetworkNewRepository;
        $this->socialNetworkProviderManager = $socialNetworkProviderManager;
    }

    /**
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function indexAction()
    {
        $libraries = $this->libraryRepository->findBy([], ['position' => 'ASC']);
        /** @var SocialNetwork $social */
        $social = $this->socialNetworkRepository->findByLikeSocial('instagram');
        if ($social) {
            $medias   = $this->socialNetworkProviderManager->getMedias($social->getNetwork(), 12);
            $variable = $social->getNetwork();
        } else {
            $social = $this->socialNetworkNewRepository->findByLikeSocial('instagram');
            if ($social) {
                $medias   = $this->socialNetworkProviderManager->getMedias($social->getNetwork(), 12);
                $variable = $social->getNetwork();
            } else {
                $medias   = [];
                $variable = 'instagram';
            }
        }

        return $this->render(
            'library.html.twig',
            [
                'classMenu' => 'black',
                'libraries' => $libraries,
                $variable   => $medias,
            ]
        );
    }
}
