<?php

namespace Concrete\Core\Entity\OAuth;

use Concrete\Core\Entity\Express\EntityRepository;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;

class ClientRepository extends EntityRepository implements ClientRepositoryInterface
{

    /**
     * Get a client.
     *
     * @param string $clientIdentifier The client's identifier
     * @param string $grantType The grant type used
     * @param null|string $clientSecret The client's secret (if sent)
     * @param bool $mustValidateSecret If true the client must attempt to validate the secret if the client
     *                                        is confidential
     *
     * @return ClientEntityInterface
     * @throws OAuthServerException
     */
    public function getClientEntity($clientIdentifier, $grantType = null, $clientSecret = null, $mustValidateSecret = true)
    {
        /** @var ClientEntityInterface $client */
        $client = $this->findOneBy(['clientKey' => $clientIdentifier]);

        // Handle client not found
        if (!$client) {
            throw OAuthServerException::invalidCredentials();
        }

        // Handle validation


        return $client;
    }

    /**
     * Validate a client's secret.
     *
     * @param string      $clientIdentifier The client's identifier
     * @param null|string $clientSecret     The client's secret (if sent)
     * @param null|string $grantType        The type of grant the client is using (if sent)
     *
     * @return bool
     */
    public function validateClient($clientIdentifier, $clientSecret, $grantType)
    {
        /** @var ClientEntityInterface $client */
        $client = $this->findOneBy(['clientKey' => $clientIdentifier]);

        // Probably need to add grant type validation

        if($client->getClientSecret() && $clientSecret) {
            return password_verify($clientSecret, $client->getClientSecret());
        }

        return false;
    }

    /**
     * @inheritdoc
     * @return \Concrete\Core\Entity\OAuth\Client
     */
    public function find($id, $lockMode = null, $lockVersion = null)
    {
        return parent::find($id, $lockMode, $lockVersion); // TODO: Change the autogenerated stub
    }

}
