<?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 WriteTextAI\WriteTextAI\Model\SettingManager;
use WriteTextAI\WriteTextAI\Helper\Data as DataHelper;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class LocationsImport extends Command
{
    /**
     * @var SettingManager
     */
    protected $settingsManager;

    /**
     * @var State
     */
    protected $appState;

    /**
     * @var DataHelper
     */
    protected $dataHelper;

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

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this->setName('writetextai:import_locations')
             ->setDescription('Import locations from api');
    }

    /**
     * @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->settingsManager->syncSetting('locations');

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

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

        return 0;
    }
}
