<?php

declare(strict_types=1);

namespace Inside\BCLH\Console;

use Illuminate\Console\Command;
use Inside\BCLH\Facades\Pdf;
use Inside\BCLH\Services\PdfService;
use Inside\Permission\Facades\Permission;
use Log;
use Symfony\Component\Console\Style\SymfonyStyle;

final class GeneratePdfsCommand extends Command
{
    /**
     * @var string
     */
    protected $name = 'bclh:pdfs';

    /*
   * @var string
   */
    protected $signature = 'bclh:pdfs {--type=} {--uuid=}';

    /**
     * @var string
     */
    protected $description = 'Generate all pdfs';

    /**
     * Import users
     */
    public function handle(): void
    {
        $contentTypes = ['folders', 'sops', 'rops', 'documents', 'declined_documents', 'pages'];

        /** @var string|null $type */
        $type = $this->option('type');

        if ($type) {
            $contentTypes = [$type];
        }

        /** @var string $uuid */
        $uuid = $this->option('uuid');

        $contents = [];
        $count = 0;

        foreach ($contentTypes as $contentType) {
            $contents[$contentType] = [];
            if ($uuid) {
                $models = call_user_func(type_to_class($contentType).'::query')->where('uuid', $uuid)->get();
            } else {
                $models = call_user_func(type_to_class($contentType).'::all');
            }

            if (count($models) === 0) {
                continue;
            }

            $contents[$contentType] = $models;
            $count += count($models);
        }

        $this->info(sprintf('Processing %d %s', $count, str_plural('pdf', $count)));

        /** @var SymfonyStyle $output */
        $output = $this->getOutput();
        $bar = $output->createProgressBar($count);

        $bar->setFormat("%message%\n %current%/%max% [%bar%] %percent:3s%%");

        Permission::disableAllowedScope();
        foreach ($contentTypes as $contentType) {
            foreach ($contents[$contentType] as $content) {
                $bar->setMessage(sprintf('%s => %s (%s)', $contentType, trim($content->title), $content->uuid));
                Pdf::generatePdf($contentType, $content->uuid, true);
                $bar->advance();
            }
        }

        $this->info("\nAll pdfs have been regenerated.");
    }
}
