<?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 CmdImportDinAssetsTest extends Command
{
    protected static $defaultName = 'app:import-din-assets-test';

    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);


        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';

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

                    $uniqueKey = $rowData[1] . $rowData[2] . $rowData[3];
                    if (!array_key_exists($uniqueKey, $uniqueTasks)) {
                        $uniqueTasks[$uniqueKey] = 1;
                    } else {
                        $errors[] = "$dinNumber -> $uniqueKey Zeile: $row";
                    }
                }
            }
        }

        return Command::SUCCESS;
    }

}