<?php
namespace App\Command;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use App\Websocket\MessageHandler;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use App\Service\MailService;

class WebsocketServerCommand extends Command
{
    private $container;
    private $em;
    private $mail;

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

    protected function configure()
    {
        $this
            ->setName('app:Websocket')
            ->setDescription('Lauch Websocket server')
            ->setHelp('Lauch Websocket server')
            ->addOption('name',null,InputOption::VALUE_REQUIRED,'Websocket server name',null)
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $port = $this->container->getParameter('wss_port');
        
        $output->writeln("Starting server on port " . $port);
        $server = IoServer::factory(
            new HttpServer(
                new WsServer(
                    new MessageHandler($this->container,$this->em,$this->mail)
                )
            ),
            $port
        );
        $server->run();
        return Command::SUCCESS;
    }
}