<?php

namespace Bastion\Handlers;

use Openguru\OpenCartFramework\Config\Settings;
use Openguru\OpenCartFramework\Http\JsonResponse;
use Psr\Log\LoggerInterface;

class LogsHandler
{
    private Settings $settings;
    private LoggerInterface $logger;

    public function __construct(Settings $settings, LoggerInterface $logger)
    {
        $this->settings = $settings;
        $this->logger = $logger;
    }

    public function getLogs(): JsonResponse
    {
        $data = [];

        $logsPath = $this->findLastLogsFileInDir(
            $this->settings->get('logs.path')
        );

        if ($logsPath) {
            $data = implode(PHP_EOL, $this->readLastLogsRows($logsPath, 100));
        }

        return new JsonResponse(compact('data'));
    }

    private function readLastLogsRows(string $path, int $lines = 1000, int $buffer = 4096): array
    {
        $f = fopen($path, 'rb');
        if (! $f) {
            return [];
        }

        $lineCount = 0;
        $chunk = '';

        fseek($f, 0, SEEK_END);
        $filesize = ftell($f);

        while ($filesize > 0 && $lineCount < $lines) {
            $seek = max($filesize - $buffer, 0);
            $readLength = $filesize - $seek;

            fseek($f, $seek);
            $chunk = fread($f, $readLength) . $chunk;

            $filesize = $seek;
            $lineCount = substr_count($chunk, "\n");
        }

        fclose($f);

        $linesArray = explode("\n", $chunk);

        return array_slice($linesArray, -$lines);
    }

    private function findLastLogsFileInDir(string $dir): ?string
    {
        $files = glob($dir . '/telecart-*.log');

        return $files ? end($files) : null;
    }
}
