<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Command;

use Chill\PersonBundle\Service\Import\SocialWorkMetadataInterface;
use Doctrine\ORM\EntityManagerInterface;
use League\Csv\Reader;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

final class ImportSocialWorkMetadata extends Command
{
    protected EntityManagerInterface $em;

    public function __construct(
        protected SocialWorkMetadataInterface $importer,
    ) {
        parent::__construct('chill:person:import-socialwork');
    }

    protected function configure()
    {
        $description = 'Imports a structured table containing social issues, social actions, objectives, results and evaluations.';
        $help = 'File to csv format, no headers, semi-colon as delimiter, datas sorted by alphabetical order, column after column.'.PHP_EOL
            .'Columns are: social issues parent, social issues child, social actions parent, social actions child, goals, results, evaluations.'.PHP_EOL
            .PHP_EOL
            .'See social_work_metadata.csv as example.'.PHP_EOL;

        $this
            ->setName('chill:person:import-socialwork')
            ->addOption('filepath', 'f', InputOption::VALUE_REQUIRED, 'The file to import.')
            ->addOption('language', 'l', InputOption::VALUE_OPTIONAL, 'The default language')
            ->setHelp($help);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $filepath = $input->getOption('filepath');

        try {
            $csv = Reader::from($filepath);
        } catch (\Throwable $e) {
            throw new \Exception('Error while loading CSV.', 0, $e);
        }

        $csv->setDelimiter(';');

        return true === $this->importer->import($csv) ?
            0 :
            1;
    }
}
