<?php
namespace Opentalent\OtConnect\Service;

use DateTime;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use TYPO3\CMS\Core\Crypto\Random;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;

/**
 * Authentication service based on the Opentalent API.
 * See the README for more
 */
class OtAuthenticationService extends AbstractAuthenticationService
{

    CONST DOMAIN = 'https://api.opentalent.fr';
    CONST API_URI = self::DOMAIN . '/api/';
    CONST LOGIN_URI = self::API_URI . 'login_check';
    CONST GET_USER_DATA_URI = self::API_URI . 'user/datafortypo3';
    CONST ISAUTH_URI = self::API_URI . 'user/isauthenticated';
    CONST LOGOUT_URI = self::API_URI . 'logout';

    // Cookies'domain needs to be the same that the api's cookies, or guzzle will ignore them.
    CONST COOKIE_DOMAIN = '.opentalent.fr';

    CONST PRODUCT_MAPPING = [
        "school-standard" => 1, // Association writer basic
        "artist-standard" => 1, // Association writer basic
        "school-premium" => 3, // Association writer full
        "artist-premium" => 3, // Association writer full
        "manager-standard" => 3, // Association writer full
    ];

    /**
     * The time in seconds during which the user's data in DB won't be re-updated after the last successful update
     * Set it to 0 to disable the delay
     */
    CONST USER_UPDATE_DELAY = 300;

    /**
     * 0 - Authentification failed, no more services will be called...
     * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
     *
     * @var int
     */
    const STATUS_AUTHENTICATION_FAILURE = 0;

    /**
     * 100 - OK, but call next services...
     * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
     *
     * @var int
     */
    const STATUS_AUTHENTICATION_CONTINUE = 100;

    /**
     * 200 - authenticated and no more checking needed
     * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
     *
     * @var int
     */
    const STATUS_AUTHENTICATION_SUCCESS = 200;

    /**
     * Guzzle Client
     *
     * @see http://docs.guzzlephp.org/en/stable/
     * @var Client
     */
    private $client;

    /**
     * Guzzle Cookie Jar
     *
     * @var CookieJar
     */
    private $jar;

    /**
     * OtAuthenticationService constructor.
     */
    public function __construct() {
        $this->jar = new CookieJar;
        $this->client = new Client(['base_uri' => self::DOMAIN, 'cookies' => $this->jar]);
    }

    /**
     * This function returns the user record back to the AbstractUserAuthentication.
     * It does not mean that user is authenticated, it only means that user is found.
     * /!\ The 'getUser' method is required by the Typo3 authentification system
     * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
     *
     * @return array|bool User record or false (content of fe_users/be_users as appropriate for the current mode)
     */
    public function getUser()
    {

        // Does the user already have a session on the Opentalent API?
        $username = $this->getAuthenticatedUsername();

        if ($username != null && $this->authInfo['loginType'] == 'FE' && $this->login['status'] === 'logout') {
            // This is a logout request
            $this->logout();
            return false;
        }

        if ($username != null && $this->login['status'] === 'login' && $this->login['uname'] != $username) {
            // The user trying to log in is not the one authenticated on the Opentalent API
            // We let the TYPO3 auth service handle it
            return false;

        } else if ($username == null && $this->login['status'] != 'login') {
            // The user has no current session on Opentalent.fr and this is not a login request
            return false;

        } else if ($this->login['status'] === 'login' && $this->login['uname'] && $this->login['uident']) {
            // This is a login request
            $username = $this->login['uname'];
            $password = $this->login['uident'];

            // Send a login request for the user to the Opentalent Api, and return the data
            // of the matching user, or false if le login failed
            $logged = $this->logUser($username, $password);
            if (!$logged) {
                return false;
            }
        }

        // Request the latest data for the user and write it in the Typo3 DB
        //   * The shouldUserBeUpdated() method checks if the user was already
        //   generated in the last minutes, to avoid unecessary operations *
        if ($this->shouldUserBeUpdated($username)) {
            $wasUpdated = $this->createOrUpdateUser();
            if (!$wasUpdated) {
                // An error happened during the update of the user's data
                // since its data may have changed (credentials, rights, rôles...)
                // we can't allow him to connect.
                return false;
            }
        }

        // No need to check Pid for those users
        $this->authInfo['db_user']['checkPidList'] = '';
        $this->authInfo['db_user']['check_pid_clause'] = '';

        // Fetch the typo3 user from the database
        return $this->fetchUserRecord($username, '', $this->authInfo['db_user']);
    }

    /**
     * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
     *
     * @return string|null
     * @throws GuzzleException
     */
    protected function getAuthenticatedUsername() {

        $this->fillCookieJar();
        try {
            $response = $this->client->request('GET', self::ISAUTH_URI, ['cookies' => $this->jar]);

            if ($response->getStatusCode() != 200) {
                return null;
            }

            return json_decode((string)$response->getBody());

        } catch (RequestException $e) {
            return null;
        }

    }

    /**
     * Update the guzzle cookie jar with the current session's ones
     */
    private function fillCookieJar() {

        foreach (['BEARER', 'SFSESSID'] as $cookieName) {
            if (array_key_exists($cookieName, $_COOKIE) &&
                $this->jar->getCookieByName($cookieName) == null) {

                $cookie = new SetCookie();
                $cookie->setName($cookieName);
                $cookie->setValue($_COOKIE[$cookieName]);
                $cookie->setDomain(self::COOKIE_DOMAIN);
                $this->jar->setCookie($cookie);
            }
        }
    }

    /**
     * Submit a login request to the API
     *
     * @param string $username
     * @param string $password
     * @return bool     Returns true if the api accepted the login request
     * @throws GuzzleException
     */
    protected function logUser($username, $password) {

        try {
            $response = $this->client->request(
                'POST',
                self::LOGIN_URI,
                ['form_params' => ['_username' => $username, '_password' => $password]]
            );

            if ($response->getStatusCode() != 200) {
                return false;
            }

            // The API accepted the login request

            // Set the cookies returned by the Api  (SESSID and BEARER)
            $this->setCookiesFromApiResponse($response);
            return true;

        } catch (RequestException $e) {
            return false;
        }
    }

    /**
     * Get the cookies from the API response and set them
     *
     * @param $response
     */
    private function setCookiesFromApiResponse($response) {

        foreach ($response->getHeader('Set-Cookie') as $cookieStr) {
            $cookie = SetCookie::fromString($cookieStr);

            $name = $cookie->getName();
            $value = $cookie->getValue();
            $expires = $cookie->getExpires();
            $path = $cookie->getPath();
            $domain = self::COOKIE_DOMAIN;
            $secure = $cookie->getSecure();
            $httpOnly = $cookie->getHttpOnly();

            setcookie($name, $value, $expires, $path, $domain, $secure, $httpOnly);
        }
    }

    /**
     * Compare the last update date for the user to the GENERATION_DELAY delay
     * and return wether the user's data may be created/updated in the Typo3 DB
     *
     * @param string $username
     * @return bool
     */
    protected function shouldUserBeUpdated($username) {

        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('fe_users');
        $q = $connection->select(['tx_otconnect_generationDate'], 'fe_users', ['username' => $username]);
        $strGenDate = $q->fetch(3)[0];

        $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
        if ($genDate == null) {
            return true;
        }
        $now = new DateTime();
        $diff = $now->getTimestamp() - $genDate->getTimestamp();

        return ($diff > self::USER_UPDATE_DELAY);
    }

    /**
     * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
     * and the Backend-user (table 'be_users', only if is admin)
     * with the data fetched from the Api
     *
     * @return bool
     */
    protected function createOrUpdateUser() {

        // Get user's data from the API
        $userApiData = $this->getUserData();

        if (empty($userApiData)) {
            // An error happened, and even if the user was logged, we can not continue
            // (user's data and rights could have changed)
            return false;
        }

        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('fe_users');

        // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
        $randomStr = (new Random)->generateRandomHexString(10);

        // Front-end user
        $fe_row = [
            'username' => $userApiData['username'],
            'password' => $randomStr,
            'name' => $userApiData['name'],
            'first_name' => $userApiData['first_name'],
            'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] FE User',
            'tx_otconnect_opentalentId' => $userApiData['id'],
            'tx_otconnect_generationDate' => date('Y/m/d H:i:s')
        ];

        // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
        $q = $connection->select(['uid'], 'fe_users', ['tx_otconnect_opentalentId' => $userApiData['id']]);
        $uid = $q->fetch(3)[0];
        if (!$uid) {
            // No existing user: create
            $connection->insert('fe_users', $fe_row);
        } else {
            // User exists: update
            $connection->update('fe_users', $fe_row, ['uid' => $uid]);
        }

        // Back-end user: only if admin
        foreach ($userApiData['accesses'] as $access) {

            //<<<<< for testing purpose TODO: remove
            $access['admin_access'] = 'true';
            // >>>>>

            if ($access['admin_access'] == 'true') {

                $be_row = [
                    'username' => $userApiData['username'],
                    'password' => $randomStr,
                    'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $access['subDomain'] . ' (id: ' . $access['id'] . ')',
//                    'avatar' => $userApiData['profile']['avatar'],
                    'lang' => 'fr',
                    'usergroup' => isset(self::PRODUCT_MAPPING[$access['product']]) ? self::PRODUCT_MAPPING[$access['product']] : 1,
                    'tx_otconnect_opentalentId' => $userApiData['id'],
                    'tx_otconnect_organizationId' => $access['organizationId'],
                    'tx_otconnect_generationDate' => date('Y/m/d H:i:s')
                ];

                $q = $connection->select(['uid'], 'be_users', ['tx_otconnect_opentalentId' => $userApiData['id']]);
                $uid = $q->fetch(3)[0];
                if (!$uid) {
                    // No existing user: create
                    $connection->insert('be_users', $be_row);
                } else {
                    // User exists: update
                    $connection->update('be_users', $be_row, ['uid' => $uid]);
                }
            }
        }

        return true;
    }

    /**
     * Get the data for the current authenticated user from the API
     *
     * @return array
     */
    protected function getUserData() {
        $this->fillCookieJar();
        try {
            $response = $this->client->request('GET', self::GET_USER_DATA_URI, ['cookies' => $this->jar]);
        } catch (RequestException $e) {
            return [];
        } catch (GuzzleException $e) {
            return [];
        }
        return json_decode($response->getBody(), true);
    }

    /**
     * Authenticates user using Opentalent auth service.
     * /!\ The 'authUser' method is required by the Typo3 authentification system
     * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
     *
     * @param array $user Data of user.
     * @return int        Code that shows if user is really authenticated.
     * @throws GuzzleException
     */
    public function authUser(array $user)
    {
        if ($user['username'] == $this->getAuthenticatedUsername()) {
            // Tha API just validated this user's auth
            return self::STATUS_AUTHENTICATION_SUCCESS;

        } else if ($this->authInfo['loginType'] === 'FE') {
            return self::STATUS_AUTHENTICATION_FAILURE;

        } else if (isset($user['tx_otconnect_opentalentId']) and $user['tx_otconnect_opentalentId'] != null) {
            // This is a user from the Opentalent DB, and the API refused its auth
            // (For performance only, since the password stored in the Typo3 is a random string,
            //  the auth will be refused by the other services anyway)
            return self::STATUS_AUTHENTICATION_FAILURE;
        }
        // This may be a user using another auth system
        return self::STATUS_AUTHENTICATION_CONTINUE;
    }

    /**
     * Send a logout request to the API, remove the sessions cookies then logout
     * /!\ Frontend only
     */
    public function logout() {
        try {
            $response = $this->client->request(
                'GET',
                self::LOGOUT_URI
            );

            if ($response->getStatusCode() != 200) {
                return false;
            }

            // The API accepted the logout request

            // Unset the session cookies (SESSID and BEARER)
            if (isset($_COOKIE['BEARER'])) {
                unset($_COOKIE['BEARER']);
                $this->unset_cookie('BEARER');
            }
            if (isset($_COOKIE['SFSESSID'])) {
                unset($_COOKIE['SFSESSID']);
                $this->unset_cookie('SFSESSID');
            }

            $this->pObj->logoff();
            return true;

        } catch (RequestException $e) {
            return false;
        } catch (GuzzleException $e) {
            return false;
        }
    }

    /**
     * Unset a cookie by reducing its expiration date
     *
     * @param string $name
     * @return bool
     */
    protected function unset_cookie(string $name) {
        $res = setcookie($name, '', time() - 1, '/', self::COOKIE_DOMAIN);
        if (!$res) {
            $this->writeLogMessage('Error while unsetting ' . $name . ' cookie');
        }
        return $res;
    }

    /**
     * Writes log message. Destination log depends on the current system mode.
     * For FE the function writes to the admin panel log. For BE messages are
     * sent to the system log. If developer log is enabled, messages are also
     * sent there.
     *
     * This function accepts variable number of arguments and can format
     * parameters. The syntax is the same as for sprintf()
     *
     * @param string $message Message to output
     * @param array<int, mixed> $params
     * @see \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
     */
    public function writeLogMessage($message, ...$params)
    {
        if (!empty($params)) {
            $message = vsprintf($message, $params);
        }
        if (TYPO3_MODE === 'BE') {
            GeneralUtility::sysLog($message, 'ot_connect');
        } else {
            /** @var TimeTracker $timeTracker */
            $timeTracker = GeneralUtility::makeInstance(TimeTracker::class);
            $timeTracker->setTSlogMessage($message);
        }
    }
}
