<?php declare(strict_types=1);

namespace Newland\AssetsNeos\Command;

use Neos\Flow\Cli\CommandController;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use function Safe\getcwd;

class AssetsCommandController extends CommandController
{
    protected const IGNORED_FILENAMES = [
        '.chunk.js',
        '.bundle.js',
        '.map',
        '.css',
        'package.json',
        'package-lock.json',
        '.lock',
        '.log',
        'composer.json',
        'toubiz-styleguide',
        'node_modules',
        'Packages/Libraries',
        'Data/Temporary',
        'AssetsCommandController.php',
        '.md',
        '/dist/',
        'Makefile',
    ];

    public function searchOutdatedCommand(string $folder = null): void
    {
        $folder = $folder ?? (getcwd() . '/Packages');
        $this->outputLine(sprintf('Searching %s for outdated asset references', $folder));

        $finder = (new Finder())
            ->in($folder)
            ->notPath([ 'node_modules', 'Packages/Libraries' ])
            ->contains('toubiz-styleguide');

        $progress = new ProgressBar($this->output->getOutput());
        $progress->start($finder->count());

        $files = [];
        foreach ($finder as $file) {
            $progress->advance();

            /** @var SplFileInfo $file */
            if ($this->isIgnored((string) $file->getRealPath())) {
                continue;
            }

            $files[] = $file->getRealPath();
        }

        $this->outputLine("\n\n");
        if (\count($files) > 0) {
            $this->outputLine('The following files contain references to toubiz-styleguide:');
            foreach ($files as $file) {
                $this->outputLine(sprintf('* %s', $file));
            }
        } else {
            $this->outputLine('No references to toubiz-styleguide found.');
        }
    }

    private function isIgnored(string $filePath): bool
    {
        $regexParts = array_map(function (string $item) {
            return '.*' . preg_quote($item, '/') . '.*';
        }, static::IGNORED_FILENAMES);
        $regex = '/(' . implode('|', $regexParts) . ')/';
        return \Safe\preg_match($regex, $filePath, $matches) === 1;
    }
}
