<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Console\Command;

use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use WriteTextAI\WriteTextAI\Model\Keywords\ReuploadThumbnails as ReuploadThumbnailsModel;

class ReuploadThumbnails extends Command
{
    /**
     * @var State
     */
    protected $appState;

    /**
     * @var ReuploadThumbnailsModel
     */
    protected $reuploadThumbnailsModel;

    /**
     * Constructor.
     *
     * @param State $appState
     * @param ReuploadThumbnailsModel $reuploadThumbnailsModel
     * @param string|null $name
     */
    public function __construct(
        State $appState,
        ReuploadThumbnailsModel $reuploadThumbnailsModel,
        ?string $name = null
    ) {
        $this->appState = $appState;
        $this->reuploadThumbnailsModel = $reuploadThumbnailsModel;
        parent::__construct($name);
    }

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this->setName('writetextai:reupload_thumbnails')
             ->setDescription('Reupload thumbnails of all completed keyword optimized items');
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $this->appState->setAreaCode(Area::AREA_ADMINHTML);
        } catch (LocalizedException $exception) {
            /** @var string $message */
            $output->writeln('Area code already set');
        }

        try {
            $output->writeln('Start Import');

            $timeStart = microtime(true);

            $this->reuploadThumbnailsModel->execute();

            $timeLasted = ceil(microtime(true) - $timeStart);

            $output->writeln('End Import, Time Lasted: ' . $timeLasted . ' secs');
        } catch (\Exception $e) {
            $output->writeln('Error: ' . $e->getMessage());
        }

        return 0;
    }
}
