<?php

namespace App\Command;

use App\DTO\EmailDTO;
use App\Event\NewEmailReceivedEvent;
use SecIT\ImapBundle\Service\Imap;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class CrmEmailCheckCommand extends Command
{
    protected static $defaultName = 'crm:email:check';
    /**
     * @var Imap
     */
    private $imap;
    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    public function __construct(Imap $imap, EventDispatcherInterface $eventDispatcher, ?string $name = null)
    {
        parent::__construct($name);
        $this->imap = $imap;
        $this->eventDispatcher = $eventDispatcher;
    }

    protected function configure()
    {
        $this
            ->setDescription('Check emails');
    }

    /**
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);

        $mailbox = $this->imap->get('connection');

        $mailsIds = $mailbox->searchMailbox('ALL SINCE "23 November 2020"');

        foreach ($mailsIds as $emailId) {
	dump($emailId);            
$email = $mailbox->getMail($emailId);
		
            $body = $email->textPlain ?? $email->textHtml ?? "Empty message";
//		dump($email->to);
            $emailTo = array_filter(array_keys($email->to), function ($email) {
                return strpos($email, 'outreach_')
                    !== false;
            });
		dump($emailTo);
//            if (count($emailTo) === 0) {
//                continue;
//            }
            $dto = new EmailDTO($email->fromAddress, reset($emailTo), $body, $email->date, $email->getAttachments());
		dump($email->date, $dto->getTo());
//            $this->eventDispatcher->dispatch('event.email_received', new NewEmailReceivedEvent($dto));
        }

        $io->success(sprintf("Email checked (%d new)", count($mailsIds)));
    }
}
