<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Controller\Backend;

use Neos\Neos\Controller\Module\AbstractModuleController;

class LogController extends AbstractModuleController
{
    public function indexAction(string $activeDate = null): void
    {
        $files = $this->listFiles();

        $dates = array_keys($files);
        $activeDate = $activeDate ?? $dates[count($dates) - 1] ?? null;

        $currentLogItems = [];
        if ($activeDate) {
            $currentLogItems = $this->readLogFile($files[$activeDate]);
        }

        $this->view->assignMultiple(compact('files', 'activeDate', 'currentLogItems'));
    }

    private function listFiles(): array
    {
        $files = [];
        $paths = \Safe\glob(FLOW_PATH_DATA . '/Newland.Toubiz.Sync.Neos.log-*.json');
        foreach ($paths as $path) {
            $date = str_replace(
                [ 'Newland.Toubiz.Sync.Neos.log-', '.json' ],
                '',
                basename((string) $path)
            );
            $files[$date] = $path;
        }
        return $files;
    }

    private function readLogFile(string $path): array
    {
        $items = array_map(
            function ($line) {
                return json_decode($line, true);
            },
            explode("\n", \Safe\file_get_contents($path))
        );

        $items = array_filter(
            $items,
            function ($item) {
                return $item !== null && $item['level_name'] !== 'DEBUG';
            }
        );

        foreach ($items as &$item) {
            $item['forUser'] = array_filter(
                $item ?? [],
                function ($value, $key) {
                    return !empty($value) && \in_array($key, [ 'context', 'level_name', 'extra' ]);
                },
                ARRAY_FILTER_USE_BOTH
            );
        }

        return $items;
    }
}
