<?php

namespace Velis\Db;

use Velis\Http\Request;
use Velis\Session\SessionInterface;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class Profiler
{
    const SESSION_KEY = 'db.profiler';

    /**
     * @var Request
     */
    private $request;

    /**
     * @var SessionInterface
     */
    private $session;

    /**
     * @param Request $request
     * @param SessionInterface $session
     */
    public function __construct(Request $request, SessionInterface $session)
    {
        $this->request = $request;
        $this->session = $session;
    }

    /**
     * @param array $row
     * @return void
     */
    public function addRow(array $row)
    {
        $queriesByRequest = $this->session->get(self::SESSION_KEY);
        if (null === $queriesByRequest) {
            $queriesByRequest = [];
        }

        $requestHash = $this->request->getId();

        if (!array_key_exists($requestHash, $queriesByRequest)) {
            $queriesByRequest[$requestHash] = [
                'method' => $this->request->getMethod(),
                'url' => $this->request->getURI(),
                'queries' => [],
            ];
        }

        $queriesByRequest[$requestHash]['queries'][] = $row;

        $this->session->set(self::SESSION_KEY, $queriesByRequest);
    }

    /**
     * @return array
     */
    public function flushAllRows(): array
    {
        $queries = $this->session->get(self::SESSION_KEY);
        $this->session->set(self::SESSION_KEY, []);

        return $queries ?: [];
    }
}
