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

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Provider\SocialNetwork;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\FacebookClient;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Mailer;
use CpCreation\VitiCore\SocialNetwork\Model\SocialNetwork;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\ConnectCpCreationClient;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\CacheItem;

class FacebookFacebookProvider implements SocialNetworkProviderInterface
{
    const TYPE = 'facebook_facebook';

    /**
     * @var CacheItem
     */
    private $cache;

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

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

    /**
     * @var FacebookClient
     */
    private $client;

    /**
     * @var SocialNetworkRepository
     */
    private $socialNetworkRepository;

    /**
     * @var SocialNetwork|null|object
     */
    private $social;

    /**
     * @var Mailer
     */
    private $mailer;

    public function __construct(SocialNetworkRepository $socialNetworkRepository,
        FacebookClient $client,
        ConnectCpCreationClient $cpCreationClient,
        AdapterInterface $cache,
        Mailer $mailer
    ) {
        $this->accessToken = '';
        $this->userId      = '';
        $social            = $socialNetworkRepository->findOneBy(['network' => static::TYPE]);
        if (!$social) {
            return ;
        }
        $this->social = $social;
        $this->client = $client;
        $this->socialNetworkRepository    = $socialNetworkRepository;
        $this->cache  = $cache;
        $this->mailer = $mailer;
        $news         = $cache->getItem('news.facebook_facebook');
        if (!$news->isHit()) {
            try {
                $response          = $cpCreationClient->get('api/client_socials/'.$social->getConfiguration()['id']);
                $result            = json_decode($response->getBody()->getContents(), true);
                $this->accessToken = $result['token'];
                $this->userId      = $result['userId'];

            } catch (\Exception $e) {
                $mailer->sendErrorConnexionApiConnectSocialInstagram($e->getMessage());
            }

        }
    }


    public function getMedias($count)
    {
        $news = $this->cache->getItem('news.facebook_facebook');
        if (!$news->isHit()) {
            try {
                return [];

            } catch (\Exception $e) {

                $this->mailer->sendErrorInstagram($e->getMessage());

                return $this->social;
            }
        }

        return $news->get();

    }

    /**
     * @return string
     */
    public function getNetwork(): string
    {
        return static::TYPE;
    }
}