<?php 

namespace NPS\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Doctrine\ORM\EntityManagerInterface;
use NPS\Etc\Strings;
use NPS\Factory\UserFactory;
use NPS\Repository\UserRepository;

/**
 * Manually adds a user
 * @author Lukas Korinek
 */
class AddUserCommand extends Command
{

    /** @var UserRepository $repo  */
    private $repo;

    /** @var UserFactory $factory */
    private $factory;

    /** @var EntityManagerInterface $em */
    private $em;

    public function __construct(EntityManagerInterface $em, UserFactory $factory, UserRepository $repo)
    {
        $this->repo = $repo;
        $this->factory = $factory;
        $this->em = $em;

        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this 
            ->setName('user:add')
            ->setDescription('Manually adds a user')
            ->addArgument('email', InputArgument::REQUIRED)
            ->addArgument('username', InputArgument::REQUIRED)
            ->addArgument('password', InputArgument::REQUIRED)
            ->addArgument('role', InputArgument::OPTIONAL);
    }   

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $email = trim($input->getArgument('email'));
        $username = trim($input->getArgument('username'));
        $password = trim($input->getArgument('password'));
        $roles = $input->hasArgument('role') ? [trim(strtoupper($input->getArgument('role')))] : ['ROLE_USER'];
        
        if($this->repo->getByEmail($email))
        {
            $output->writeln('User with that email already exists');
            return 1;
        }

        if($this->factory->create($email, $username, $password, $roles))
        {
            $this->em->flush();
            return 0;
        }

        $output->writeln('Password does not meet security requirements');
        return 2;

    }
}


