<?php

namespace Lucent\Commands;

use DirectoryIterator;
use Exception;
use Illuminate\Console\Command;
use Intervention\Image\ImageManager;
use Lucent\Channel\ChannelService;
use Lucent\Schema\Schema;
use Lucent\Schema\Type;

class RebuildThumbnails extends Command
{

    protected $signature = 'lucent:rebuild:thumbnails';

    protected $description = 'Rebuilds thumbnails for path';


    public function __construct(public ImageManager $imageManager)
    {
        parent::__construct();
    }


    public function handle(ChannelService $channelService): int
    {
        $channelService->channel->schemas
            ->where("type", Type::FILES)->values()
            ->map([$this, 'rebuildThumbnails']);

        return 0;
    }

    public function rebuildThumbnails(Schema $schema): void
    {

        $filesDir = storage_path("app/public/" . $schema->path . "/");
        $thumbDir = storage_path("app/public/thumbs/" . $schema->path . "/");
        if (!file_exists($thumbDir)) {
            make_dir_r($thumbDir);
        }

        if (!file_exists($filesDir)) {
            make_dir_r($filesDir);
        }

        $filesDirIterator = new DirectoryIterator($filesDir);

        foreach ($filesDirIterator as $file) {

            if ($file->isDot()) {
                continue;
            }

            try {
                $image = $this->imageManager->make($filesDir . $file->getFilename());
            } catch (Exception $e) {
                $this->error($e->getMessage());
                continue;
            }

            $image->fit(300, 300);
            try {
                $image->encode('webp', 75)->save($thumbDir . $file->getFilename());
            } catch (Exception $e) {
                $this->error($e->getMessage());
                continue;
            }

            $this->info($file->getFilename());
        }
    }

}
