<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\Adherent;
use App\Entity\ExternalAdherentDatedData;
use App\Entity\GlobalParameter;
use App\Utils\CustomEntityManager;
use App\Utils\TAVCotisationUtils;
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 Twig\Environment;
use Symfony\Component\Console\Input\InputArgument;

/**
 * This command is used to import data to complete external adherents data
 */
class ImportExternalAdherentDatedData extends Command
{
    protected static $defaultName = 'kohinos:ssa:external-adherent-dated-data-import';

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

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

    protected function configure()
    {
        $this
            ->setDescription('SSA : importer via CSV des informations externes datées concernant les adhérents,.')
            ->addArgument('filepath', InputArgument::OPTIONAL, 'Chemin du fichier csv contenant les données datées.')
        ;
    }

    private function readCsv() {

    }

    /**
     * @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 external dated adherent data');

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

        if (($handle = fopen($csvFilePath, "r")) !== FALSE) {
            while (($row = fgetcsv($handle, 1000, ";")) !== FALSE) {
                if ($row[0] === 'mail') {
                    // headers row
                    continue;
                }

                try {
                    $adherent = $this->em->getRepository(Adherent::class)->findOneByEmail($row[0], false);
                } catch (\Exception $e) {
                    $this->io->warning('Adherent not found: ' . $row[0]);
                    continue;
                }

                $annee = $row[2];
                if(!$annee) {
                    $this->io->warning('Year not provided: ' . $row[2]);
                    continue;
                }
                $annee = intval($annee);

                $updated = false;

                $datedData = $this->em->getRepository(ExternalAdherentDatedData::class)->findBy([
                    'adherent' => $adherent,
                    'year' => $annee
                ]);

                if(!$datedData) {
                    $datedData = new ExternalAdherentDatedData();
                    $datedData->setAdherent($adherent);
                    $datedData->setYear($annee);
                    $updated = true;
                } else {
                    $datedData = $datedData[0];
                }

                #If a field is already stored in database, do not update it
                #If no data is provided in the file cell, do not fill (let it empty)
                if (!$datedData->getHouseholdUnitShares() && $row[1] !== "") {
                    $datedData->setHouseholdUnitShares(floatval($row[1]));
                    $updated = true;
                }
                if (!$datedData->getAnnualIncome() && $row[3] !== "") {
                    $datedData->setAnnualIncome(intval($row[3]));
                    $updated = true;
                }
                if (!$datedData->getMonthlyIncome() && $row[4] !== "") {
                    $datedData->setMonthlyIncome(intval($row[4]));
                    $updated = true;
                }

                if ($updated) {
                    $this->em->persist($datedData);
                    $this->io->success('Succesfully updated: ' . $row[0]);
                } else {
                    $this->io->warning('No new dated data for Adherent: '
                        . $row[0] . ' and Year: ' . $row[2] . ' (update ignored)');
                }
            }

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

        $this->io->success('End');

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

        return 0;
    }
}
