<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Sut\Domain\Tracking;

use Exception;
use Sut\Domain\Time\TimerInterface;
use Sut\Domain\Tracking\Data\TrackInterface;

class Tracker
{
    /**
     * @var HttpClientInterface
     */
    private $httpClient;

    /**
     * @var TimerInterface
     */
    private $timer;

    /**
     * @var string
     */
    private $trackUrl;

    /**
     * @var string
     */
    private const AUTHORIZATION = 'Authorization';

    /**
     * @param HttpClientInterface $httpClient
     * @param TimerInterface $timer
     * @param string $trackUrl
     */
    public function __construct(HttpClientInterface $httpClient, TimerInterface $timer, string $trackUrl)
    {
        $this->httpClient = $httpClient;
        $this->timer = $timer;
        $this->trackUrl = $trackUrl;
    }

    /**
     * @param TrackInterface $track
     * @return HttpResponse|null
     */
    public function sendData(TrackInterface $track): ?HttpResponse
    {
        try {
            return $this->httpClient->request(
                'POST',
                $this->trackUrl,
                $this->getHeaders(),
                $track->serialize()
            );
        } catch (Exception $e) {
            return null;
        }
    }

    /**
     * @return array
     * @throws Exception
     */
    private function getHeaders(): array
    {
        $token = sprintf('%s-%s-%s', random_int(1000000000, 9999999999), random_int(1000, 9999), $this->timer->time());

        return [self::AUTHORIZATION => $token];
    }
}
