<?php

namespace App\Util;

use App\Entity\User;
use App\Entity\GlobalParameter;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class WordpressUtil
{
    protected $em;
    protected $client;
    protected $apiKey = null;
    protected $isUsed = null;
    protected $url = null;

    public function __construct(EntityManagerInterface $em, HttpClientInterface $client)
    {
        $this->em = $em;
        $this->client = $client;
    }

    public function getApiKey(): string
    {
        if (null !== $this->apiKey) {
            return $this->apiKey;
        }

        $users = $this->em->getRepository(User::class)->findByRole('ROLE_API');

        return $this->apiKey = $users[0]->getApiKey() ?? '';
    }

    public function getUrl(): string
    {
        if (null !== $this->url) {
            return $this->url;
        }

        return $this->url = $this->em->getRepository(GlobalParameter::class)
                                     ->val(GlobalParameter::WORDPRESS_URL);
    }

    /**
     * Determine whether Wordpress is used or not.
     *
     * @return bool
     */
    public function isUsed(): bool
    {
        if (null !== $this->isUsed) {
            return $this->isUsed;
        }

        return $this->isUsed = (
            'true' === $this->em->getRepository(GlobalParameter::class)
                                ->val(GlobalParameter::USE_WORDPRESS)
            ? true
            : false
        );
    }

    /**
     * Determine whether synchronization with Wordpress is available or not.
     *
     * @return bool
     */
    public function canSync(): bool
    {
        return $this->isUsed() && $this->getUrl();
    }

    /**
     * Run the synchronization with Wordpress, through an API call.
     * Actually, only 'Prestataires' can be sync.
     *
     * @param array|int|null $id  If null, ask for a full sync.
     *
     * @return bool  Return false if the sync isn't run. Else true.
     */
    public function runSync($id = null): bool
    {
        if (! $this->canSync()) {
            return false;
        }

        $endpoint = sprintf("%s/%s/%s",
            $this->getUrl(),
            "wp-json/wosmpl/v1/sync_partners",
            null === $id ? '' : ('?ids=' . \implode(',', (array) $id))
        );

        $this->client->request('GET', $endpoint, [
            'headers' => [
                'API-AUTH-TOKEN' => $this->getApiKey(),
            ],
        ]);

        return true;
    }
}
