<?php

namespace App\Controller;


use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use Symfony\Component\HttpFoundation\Response;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;


class SecretariatController extends AbstractController
{


    /**
     * @Route("/secretariat", name="app.secretariat.home")
     */
    public function index(): Response
    {
        return $this->render('home/secretariat/index.html.twig', [
            'controller_name' => 'SecretariatController',
        ]);
    }

    /**
     * @Route("/secretariat_fp", name="app.secretariat.fp")
     * @throws Exception
     */
    public function fp(): Response
    {
        return $this->redirectToRoute('chimp.list');
    }



    /**
     * @Route("/secretariat_calendar", name="app.secretariat.calendar")
     * @throws Exception
     */
    public function extractCalendarData(HttpClientInterface $httpClient): Response
    {
        return $this->render('home/secretariat/calendar/index.html.twig', ['name' => 'John Doe',
            'occupation' => 'gardener']);
    }

    private function refreshTokenIfNeeded(HttpClientInterface $httpClient) :void {
        $arrayToken=$_SESSION['oauthTokenArray'];

        [
            "refresh_token" => $refresh_token,
            "expires_in"    => $expires_in,
            "created"       => $created
        ] = $arrayToken;

        // If the token is set to expire in the next 30 seconds.
        $expired = ($created + ($expires_in - 30)) < time();

        if ($expired)
        {
            $options= [
                'headers' => [
                    'Accept'        => 'application/json',
                    'Content-type'  => 'application/x-www-form-urlencoded'
                ],
                'body' => [
                    'client_id'         => $this->getParameter('app.google_client_id'),
                    'client_secret'     => $this->getParameter('app.google_client_secret'),
                    'refresh_token'     => $refresh_token,
                    'grant_type'        => 'refresh_token'
                ]

            ];
            $arrayToken= $httpClient->request('POST',OAuthController::GOOGLE_DATA_ENDPOINT,$options)->toArray();
            [
                "access_token"  => $access_token,
                "expires_in"    => $expires_in
            ] = $arrayToken;
            $oauthTokenArray["access_token"]=$access_token;
            $oauthTokenArray["refresh_token"]=$refresh_token;
            $oauthTokenArray["expires_in"]=$expires_in;
            $oauthTokenArray["created"]=time();

            $_SESSION['oauthTokenArray'] = $oauthTokenArray;


        }
    }

}
