<?php

namespace App\Command;
use App\Entity\DinAsset;
use App\Entity\DinAssetTask;
use Doctrine\ORM\EntityManagerInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\KernelInterface;


/**
 * Command to import excel that with answers of specifications
 *
 * Class CmdImportAll
 * @package App\Command
 */
class CmdImportDinAssets extends Command
{
    protected static $defaultName = 'app:import-din-assets';

    private $em;
    private $container;
    private $kernel;

    public function __construct(EntityManagerInterface $em, ContainerInterface $container, KernelInterface $kernel)
    {
        $this->em = $em;
        $this->container = $container;
        $this->kernel = $kernel;
        parent::__construct();
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     * @throws \Exception
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        ini_set('memory_limit', '4096M');
        $projectRoot = $this->kernel->getProjectDir();
        $excelFile = $projectRoot. '/import/mpp_import_din.xlsx';
        $reader = IOFactory::createReaderForFile($excelFile);
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($excelFile);

        $this->em->getConnection()->beginTransaction();

        try {
            $this->em->createQuery('DELETE FROM App\Entity\DinAssetTask')->execute();
            $this->em->createQuery('DELETE FROM App\Entity\DinAsset')->execute();

            $dinAssetsByDinAndName = [];

            foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
                $worksheetTitle = $worksheet->getTitle();

                $dinNumber = (int) $worksheetTitle;
                $isDinWorksheet = $dinNumber >= 100 && $dinNumber < 1000;

                if ($isDinWorksheet) {

                    $highestRow = $worksheet->getHighestRow();
                    $highestColumn = $worksheet->getHighestColumn();

                    $startRow = 3;
                    $startCol = 'A';

                    for ($row = $startRow; $row <= $highestRow; $row++) {
                        $rowData = [];
                        for ($col = $startCol; $col <= $highestColumn; $col++) {
                            $cell = $worksheet->getCell($col . $row);
                            $rowData[] = $cell->getValue();
                        }

                        $dinNumber = $rowData[0];

                        if (null === $dinNumber) {
                            break;
                        }
                        $name = $rowData[1];
                        $key = $dinNumber.$name;
                        if (!array_key_exists($key, $dinAssetsByDinAndName)) {
                            $dinAsset = new DinAsset();
                            $dinAsset->setDinNumber($rowData[0]);
                            $dinAsset->setName($rowData[1]);
                            $dinAsset->setCycleMonthsMin($rowData[11]);
                            $dinAsset->setCycleMonthsMax($rowData[12]);
                            $this->em->persist($dinAsset);
                            $this->em->flush();
                            $dinAssetsByDinAndName[$key] = $dinAsset;
                        }
                        $dinAsset = $dinAssetsByDinAndName[$key];
                        $dinAssetTask = new DinAssetTask();
                        $dinAssetTask->setDinAsset($dinAsset);
                        $dinAssetTask->setDelimitation($rowData[2]);
                        $dinAssetTask->setTask($rowData[3]);
                        $dinAssetTask->setInspection($rowData[4] !== null);
                        $dinAssetTask->setMaintenance($rowData[5] !== null);
                        $dinAssetTask->setService($rowData[6] !== null);
                        $dinAssetTask->setExpert($rowData[7] !== null);
                        $dinAssetTask->setSpecialist($rowData[8] !== null);
                        $dinAssetTask->setSkilledPersonnel($rowData[9] !== null);
                        $dinAssetTask->setNorm($rowData[10]);
                        $this->em->persist($dinAssetTask);
                        $this->em->flush();
                    }
                }
            }
            $this->em->flush();

        } catch (\Exception $e) {
            echo "$dinNumber $row ".$e->getMessage();
            $this->em->getConnection()->rollBack();
            return Command::FAILURE;
        }
        $this->em->getConnection()->commit();

        return Command::SUCCESS;
    }

}