<?php

namespace App\Command;
use App\Entity\Question;
use App\Entity\QuestionType;
use App\Utils\Utils;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
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 CmdImportQuestions extends Command
{
    protected static $defaultName = 'app:import-questions';

    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)
    {
        $questionTypesByType = Utils::getSortedObjects('getType', $this->em->getRepository(QuestionType::class)->findAll());
        if (($handle = fopen($this->kernel->getProjectDir().'/import/questions.csv', 'r')) !== FALSE) {
            /** @var Connection $connection */
            $this->em->getConnection()->beginTransaction();
            $row = 1;
            try {
                while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
                    if ($row !== 1) {
                        if (!array_key_exists($data[0], $questionTypesByType)) {
                            throw new \Exception('question type not found');
                        }
                        /** @var QuestionType $qType */
                        $qType = $questionTypesByType[$data[0]];
                        $question = new Question($qType);
                        $question->setQuestionText($data[1]);
                        $question->setWeight($data[2]);
                        $this->em->persist($question);
                    }
                    $row++;
                }
                $this->em->flush();
                $this->em->getConnection()->commit();
                fclose($handle);
            } catch (\Exception $e) {
                $this->em->getConnection()->rollBack();
            }

        }
        return Command::SUCCESS;
    }

}