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

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\BasicInstagramClient;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\ConnectCpCreationClient;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\InstagramClient;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Mailer;
use CpCreation\VitiCore\SocialNetwork\Model\SocialNetwork;
use CpCreation\VitiCore\SocialNetwork\Model\SocialNetworkNew;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkNewRepository;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
use Doctrine\ORM\EntityManagerInterface;
use GuzzleHttp\Psr7\Uri;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\CacheItem;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Service\EncryptOpenSSl;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;

class BasicInstagramProvider implements SocialNetworkProviderInterface
{
    const TYPE = 'basic_instagram';


    private $cache;
    private $accessToken;
    private $userId;
    private $socialNetworkNewRepository;
    private $client;
    private $social;
    private $cpCreationClient;
    private $apiInstagramClient;
    private $encrypt;
    private $router;
    private $em;
    private $mailer;
    private $clientIdAppInstagram;

    public function __construct(SocialNetworkNewRepository $socialNetworkNewRepository,
        BasicInstagramClient $client,
        ConnectCpCreationClient $cpCreationClient,
        InstagramClient $apiInstagramClient,
        AdapterInterface $cache,
        EntityManagerInterface $em,
        EncryptOpenSSl $encrypt,
        RouterInterface $router,
        Mailer $mailer,
        $clientIdAppInstagram
    ) {

        $this->accessToken = '';
        $this->userId      = '';
        /** @var SocialNetworkNew $social */
        $social                     = $socialNetworkNewRepository->findOneBy(['network' => static::TYPE]);
        $this->social               = $social;
        $this->cpCreationClient     = $cpCreationClient;
        $this->apiInstagramClient   = $apiInstagramClient;
        $this->client               = $client;
        $this->em                   = $em;
        $this->router               = $router;
        $this->encrypt              = $encrypt;
        $this->clientIdAppInstagram = $clientIdAppInstagram;
        if (!$social) {
            return;
        }
        $this->socialNetworkNewRepository = $socialNetworkNewRepository;
        $this->cache                      = $cache;
        $this->mailer                     = $mailer;
        $news                             = $cache->getItem('news.instagram');
        if (!$news->isHit()) {
            try {

                $response          = $this->cpCreationClient->get('api/client_socials/'.$social->getConnectId());
                $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.instagram');
        if (!$news->isHit()) {
            try {
                $result   = $this->client->get(
                    'me/media', [
                        'query' => [
                            'access_token' => $this->accessToken,
                            'fields'       => 'id,caption,media_type,media_url,permalink,timestamp,thumbnail_url,username',
                            'limit'  => $count,
                        ],
                    ]
                );
                $response = json_decode($result->getBody()->getContents());
                $news->expiresAfter(180);
                $this->social->setData($response->data);
                $this->socialNetworkNewRepository->save($this->social);
                $this->cache->save($news->set($response));

                return $response;

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

                return $this->social;
            }
        }

        return $news->get();
    }

    public function loginUrl(Request $request)
    {
        /** @var Uri $uri */
        $uri          = $this->cpCreationClient->getConfig()['base_uri'];
        $redirectUri  = $uri->getScheme().'://'.$uri->getHost().$uri->getPath().'request/instagram/callback';
        $encryptedUri = $this->encrypt->encrypt($request->getScheme().'://'.$request->getHost().$this->router->generate('admin_socialNew'));
        $params       = [
            'client_id'     => $this->clientIdAppInstagram,
            'redirect_uri'  => $redirectUri,
            'scope'         => 'instagram_business_basic,instagram_business_content_publish',
            'response_type' => 'code',
            'state'         => $encryptedUri,
        ];
        /** @var Uri $uriApiInstagram */
        $uriApiInstagram = $this->apiInstagramClient->getConfig()['base_uri'];
        //dd($this->apiInstagramClient->getConfig());
        //dd($uriApiInstagram->getScheme().'://'.$uriApiInstagram->getHost().$uriApiInstagram->getPath().'oauth/authorize?'.http_build_query($params));

        return $uriApiInstagram->getScheme().'://'.$uriApiInstagram->getHost().$uriApiInstagram->getPath().'oauth/authorize?'.http_build_query($params);
    }

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