<?php

namespace KupShop\MetricsBundle\Util;

use Doctrine\DBAL\Logging\SQLLogger;

/**
 * Includes executed SQLs in a Debug Stack.
 */
class SQLTransactionDebugger implements SQLLogger
{
    /** @var float|null */
    public $start;

    /** @var int */
    public $currentQuery = 0;

    /** @var float */
    public $time = 0.;

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

    public function __construct(?string $debugFilePath = null)
    {
        $this->debugFilePath = $debugFilePath ?? (__DIR__.'/SQLTransactionDebug.log');
    }

    public function startQuery($sql, ?array $params = null, ?array $types = null)
    {
        if ($sql != 'SHOW ENGINE INNODB STATUS;') {
            // log query
            file_put_contents($this->debugFilePath, PHP_EOL.PHP_EOL.'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'.PHP_EOL.$sql.PHP_EOL, FILE_APPEND | LOCK_EX);

            // log info
            $skip = true;
            $dbInfo = sqlQuery('SHOW ENGINE INNODB STATUS;')->fetchColumn(2);
            foreach (explode(PHP_EOL, $dbInfo) as $row) {
                if (!$skip && $row === 'FILE I/O') {
                    $skip = true;
                } elseif (!$skip) {
                    file_put_contents($this->debugFilePath, $row.PHP_EOL, FILE_APPEND | LOCK_EX);
                }
                if ($row === 'TRANSACTIONS') {
                    $skip = false;
                }
            }
        }

        $this->start = \microtime(true);
    }

    public function stopQuery()
    {
        $this->time += \microtime(true) - $this->start;
    }
}
