<?php

namespace Lc\SovBundle\Builder\Ticket;

use Doctrine\ORM\EntityManagerInterface;
use Lc\SovBundle\Event\Ticket\TicketEvent;
use Lc\SovBundle\Notification\MailMailjetNotification;
use Lc\SovBundle\Component\FormComponent;
use Lc\SovBundle\Factory\Ticket\TicketFactory;
use Lc\SovBundle\Factory\Ticket\TicketMessageFactory;
use Lc\SovBundle\Model\Ticket\TicketInterface;
use Lc\SovBundle\Model\Ticket\TicketMessageInterface;
use Lc\SovBundle\Model\Ticket\TicketModel;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class TicketMessageBuilder
{
    protected EntityManagerInterface $entityManager;
    protected MailMailjetNotification $mailMailjetNotification;
    protected TicketMessageFactory $ticketMessageFactory;
    protected EventDispatcherInterface $eventDispatcher;

    public function __construct(
            EntityManagerInterface $entityManager,
            MailMailjetNotification $mailMailjetNotification,
            TicketMessageFactory $ticketMessageFactory,
            EventDispatcherInterface $eventDispatcher
    ) {
        $this->entityManager = $entityManager;
        $this->mailMailjetNotification = $mailMailjetNotification;
        $this->ticketMessageFactory = $ticketMessageFactory;
        $this->eventDispatcher = $eventDispatcher;
    }

    public function create(array $params = []): TicketMessageInterface
    {
        $ticket = $params['ticket'];
        $ticketMessage = $this->ticketMessageFactory->create($ticket);

        $ticketMessage->setStatus(1);
        $ticketMessage->setTicket($ticket);
        $ticketMessage->setMessage($params['message']);
        if (isset($params['answerByAdmin']) && $params['answerByAdmin']) {
            $ticketMessage->setAnswerByAdmin($params['answerByAdmin']);
        }
        $this->entityManager->persist($ticketMessage);

        if (isset($params['imageFilename']) && $params['imageFilename']) {
            $ticketMessage->setImageFilename($params['imageFilename']);
        }
        if (isset($params['closeTicket']) && $params['closeTicket']) {
            $ticket->setStatus(TicketModel::TICKET_STATUS_CLOSED);
        }

        $ticket->setUpdatedAt(new \DateTime());

        $this->entityManager->create($ticket);
        $this->entityManager->flush();

        $this->eventDispatcher->dispatch(new TicketEvent($ticket), TicketEvent::NEW_MESSAGE_EVENT);


        return $ticketMessage;
    }

}
