<?php

namespace Lc\SovBundle\Controller\Ticket;

use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Assets;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Registry\TemplateRegistry;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Lc\SovBundle\Container\Ticket\TicketMessageContainer;
use Lc\SovBundle\Definition\ActionDefinition;
use Lc\SovBundle\Event\Ticket\TicketEvent;
use Lc\SovBundle\Form\Ticket\TicketMessageAdminFormType;
use Lc\SovBundle\Form\Ticket\TicketStatusType;
use Lc\SovBundle\Controller\AbstractAdminController;
use Lc\SovBundle\Model\Ticket\TicketModel;
use Lc\SovBundle\Repository\RepositoryQueryInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;

abstract class TicketAdminController extends AbstractAdminController
{

    public function getRepositoryQuery(): RepositoryQueryInterface
    {
        return $this->getTicketContainer()->getRepositoryQuery();
    }

    public function createEntity(string $entityFqcn)
    {
        $ticket = $this->getTicketContainer()->getFactory()->create();
        return $ticket;
    }

    public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
    {
        parent::persistEntity($entityManager, $entityInstance);
        $this->getEventDispatcher()->dispatch(new TicketEvent($entityInstance), TicketEvent::NEW_TICKET_EVENT);
    }

    public function configureCrud(Crud $crud): Crud
    {
        $crud = parent::configureCrud($crud); // TODO: Change the autogenerated stub
        $crud->setDefaultSort(array('updatedAt' => 'DESC'));
        $crud->overrideTemplate('crud/detail', '@LcSov/admin/ticket/detail.html.twig');
        return $crud;
    }


    public function configureFields(string $pageName): iterable
    {
        return $this->getTicketContainer()->getFieldDefinition()->getFields($pageName);

    }

    public function configureAssets(Assets $assets): Assets
    {
        $assets = parent::configureAssets($assets);

        $assets->addWebpackEncoreEntry('sov-ticket');

        return $assets;
    }


    public function configureActions(Actions $actions): Actions
    {
        $actions->add(Crud::PAGE_INDEX, ActionDefinition::DETAIL);
        $actions =  parent::configureActions($actions);
        $actions->disable( ActionDefinition::EDIT, ActionDefinition::DUPLICATE);
        return $actions;

    }

    public function createIndexRepositoryQuery(
            SearchDto $searchDto,
            EntityDto $entityDto,
            FieldCollection $fields,
            FilterCollection $filters
    ): RepositoryQueryInterface {
        $repositoryQuery = parent::createIndexRepositoryQuery(
                $searchDto,
                $entityDto,
                $fields,
                $filters
        );

       if(!$this->isRepositoryQueryFiltered()){

           $repositoryQuery->filterByStatus(array(
                   TicketModel::TICKET_STATUS_OPEN,
                   TicketModel::TICKET_STATUS_BEING_PROCESSED,
                   TicketModel::TICKET_STATUS_PROCESSED
            ));
       }

        return $repositoryQuery;
    }



    public function detail(AdminContext $context)
    {
        $adminUrlGenerator = $this->get(AdminUrlGenerator::class);
        $ticket = $context->getEntity()->getInstance();

        $url = $adminUrlGenerator
                ->setAction('ticketStatusAction')
                ->generateUrl();

        $formTicketStatus = $this->createForm(
                TicketStatusType::class,
                $ticket,
                [
                        'action' => $url,
                        'method' => 'POST',
                ]
        );

        $ticketMessage = $this->get(TicketMessageContainer::class)->getFactory()->create($ticket);
        $formAddTicketMessage = $this->createForm(TicketMessageAdminFormType::class, $ticketMessage);
        $formAddTicketMessage->handleRequest($this->get(RequestStack::class)->getMainRequest());

        if ($formAddTicketMessage->isSubmitted() && $formAddTicketMessage->isValid()) {
            $ticketMessage = $formAddTicketMessage->getData();
            $ticketMessage->setTicket($ticket);
            $ticketMessage->setAnswerByAdmin(true);
            $this->get(EntityManagerInterface::class)->create($ticketMessage);
            $this->get(EntityManagerInterface::class)->flush();
            $this->getEventDispatcher()->dispatch(new TicketEvent($ticket), TicketEvent::NEW_MESSAGE_EVENT);

            return $this->redirect($this->generateEaUrl());
        }

        return $this->render(
            $context->getTemplatePath('crud/detail'),
                [
                        'form_ticket_status' => $formTicketStatus->createView(),
                        'form_add_ticket_message' => $formAddTicketMessage->createView(),
                        'ticket' => $ticket,
                ]
        );
    }



    public function ticketStatusAction(AdminContext $context, EntityManagerInterface $entityManager)
    {

        $ticket = $context->getEntity()->getInstance();

        $formTicketStatusForm = $this->createForm(TicketStatusType::class, $ticket);
        $formTicketStatusForm->handleRequest($context->getRequest());

        $success = false;
        if ($formTicketStatusForm->isSubmitted() && $formTicketStatusForm->isValid()) {

            $entityManager->update($ticket);
            $entityManager->flush();
            $success = true;
        }

        return new JsonResponse(['success' => $success]);
    }

}
