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

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


use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\InstagramClient;
use CpCreation\VitiCore\SocialNetwork\Model\SocialNetwork;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\CacheItem;

class InstagramProvider implements SocialNetworkProviderInterface
{
    const TYPE = 'instagram';

    private $accessToken;

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

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

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

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

    public function __construct(SocialNetworkRepository $socialNetworkRepository,
        InstagramClient $client,
        AdapterInterface $cache
    ) {
        $social                        = $socialNetworkRepository->findOneBy(['network' => static::TYPE]);
        $this->social                  = $social;
        $this->socialNetworkRepository = $socialNetworkRepository;
        $this->client                  = $client;
        $this->cache                   = $cache;
        if (!$social) {
            return;
        }
        if (!$social->getToken()) {
            return;
        }
        $this->accessToken = $social->getToken();
    }

    public function getMedias($count)
    {
        $news = $this->cache->getItem('news.instagram');
        if (!$news->isHit()) {
            try {
                $result   = $this->client->get(
                    'users/self/media/recent', [
                        'query' => [
                            'access_token' => $this->accessToken,
                            'count'        => $count,
                        ],
                    ]
                );
                $response = json_decode($result->getBody()->getContents());
                $news->expiresAfter(60);
                $this->social->setData($response->data);
                $this->socialNetworkRepository->save($this->social);
                $this->cache->save($news->set($response));

                return $response;

            } catch (\Exception $e) {

                return $this->social;
            }
        }

        return $news->get();
    }

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