<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\ExternalDataTheoreticalCotisationRule;
use App\Utils\CustomEntityManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Question\ConfirmationQuestion;

/**
 * This command is used to import theoritical cotisation rules data from a CSV file.
 * CSV file is formated as follow, with the first row as header:
 * allocation_amount;income_min;income_max;coef;intercept;fixed_value
 */
class ImportTheoriticalCotisationRules extends Command
{
    protected static $defaultName = 'kohinos:ssa:import-theoritical-cotisation-rules';

    protected $em;
    protected $io;
    protected $param;

    public function __construct(CustomEntityManager $em) {
        $this->em = $em;
        parent::__construct();
    }

    protected function configure()
    {
        $this
            ->setDescription('SSA : importer via CSV les données utiles au calcul d\'un montant théorique de cotisation des adhérents.')
            ->addArgument('filepath', InputArgument::REQUIRED, 'Chemin du fichier csv contenant les données.')
        ;
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->io = new SymfonyStyle($input, $output);

        $this->io->title('START - importing theoritical cotisation rules');

        $csvFilePath = $input->getArgument('filepath');

        // Check if data already exist
        if ($this->em->getRepository(ExternalDataTheoreticalCotisationRule::class)->findAll()) {
            $helper = $this->getHelper('question');
            $question = new ConfirmationQuestion('Data already exists, it will be fully removed and replaced by file content. Continue? (y/N) ', false);

            if (!$helper->ask($input, $output, $question)) {
                return 0;
            }

            // Delete all records and reimport
            $this->em->getRepository(ExternalDataTheoreticalCotisationRule::class)->removeAll();
        }

        if (($handle = fopen($csvFilePath, "r")) !== FALSE) {
            while (($row = fgetcsv($handle, 1000, ";")) !== FALSE) {
                if ($row[0] === 'allocation_amount') {
                    // headers row
                    continue;
                }
                
                $data = new ExternalDataTheoreticalCotisationRule();
                $data->setAllocationAmount(intval($row[0]));

                if ($row[1] !== "") {
                    $data->setIncomeMin(floatval(str_replace(',', '.', $row[1])));
                }
                if ($row[2] !== "") {
                    $data->setIncomeMax(floatval(str_replace(',', '.', $row[2])));
                }
                if ($row[3] !== "") {
                    $data->setCoef(floatval(str_replace(',', '.', $row[3])));
                }
                if ($row[4] !== "") {
                    $data->setIntercept(floatval(str_replace(',', '.', $row[4])));
                }
                if ($row[5] !== "") {
                    $data->setFixedValue(floatval(str_replace(',', '.', $row[5])));
                }

                $this->em->persist($data);
            }

            $this->em->flush();
            fclose($handle);
        }

        $this->io->success('Data succesfully imported');

        $memoryUsage = memory_get_usage(true) / 1024 / 1024;
        $this->io->text("Batch finished with memory: ${memoryUsage}M");

        return 0;
    }
}
