<?php

namespace App\Controller\Admin;

use App\Entity\Event;
use App\Entity\EventMedia;
use App\Form\UserType;
use App\Form\EventType;
use App\Utils\RenderHelper;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityManagerInterface;
use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Component\HttpFoundation\Request;
use Omines\DataTablesBundle\Column\BoolColumn;
use Omines\DataTablesBundle\Column\TextColumn;
use Omines\DataTablesBundle\Column\TwigColumn;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Omines\DataTablesBundle\Column\TwigStringColumn;
use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

#[Route("/admin/event", name: "admin_event_")]
class EventMediasController extends AbstractController
{

    #[Route('/{event_id}/medias', name: 'medias_list', priority: 2)]
    public function medias($event_id, Request $request, DataTableFactory $dataTableFactory, EntityManagerInterface $manager)
    {   
        if (!$this->getUser()) { return $this->redirectToRoute('auth_login');}
        if (!in_array("ROLE_EDITOR", $this->getUser()->getRoles())) throw new AccessDeniedException();

        $user = $this->getUser();
        $current_event = $manager->getRepository(Event::class)->find($event_id);

        $current_role = $current_event->getRealRoleForUser($user);

        $table = $dataTableFactory->create()

            ->add('id', TextColumn::class, ['label' => 'id', 'className' => 'id'])

            ->add('videoMedia', TextColumn::class, ['visible' => false])
            ->add('imgMediaFileName', TwigStringColumn::class, [
                'label' => 'Media', 
                'className' => 'admin-list-event-media',
                // 'template' => '<img src="{{ vich_uploader_asset(row, \'imgMediaFile\') | imagine_filter_cache(\'admin_event_medias_list_filter\') }}" />',
                'template' => '<twig:ImageOrVideo entity="{{ row }}" imageFileNameField="imgMediaFileName" imageFileField="imgMediaFile" videoField="videoMedia" alt="' . $current_event->getTitle() . '" filter="admin_event_list_filter" />',


                // 'template' => '<img src="{{ vich_uploader_asset(row, \'imgMediaFile\') }}" />',
            ])

            ->add('ordre', TwigColumn::class, [
                'label' => 'Ordre', 
                'className' => 'ordre',
                'template' => 'admin/event-media/list-fields/ordre.html.twig'
            ])

            ->add('actions', TextColumn::class, ['label' => '',
                'className' => 'col-actions',
                'render' => function($value, $context) use ($current_role) {

                    $route_edit = $this->generateUrl('admin_event_media_edit', ["id" => $context->getId()]);
                    $route_delete = $this->generateUrl('admin_event_media_delete', ["id" => $context->getId()]);

                    $render = "<div class='edit-actions'>";
                    $render .= RenderHelper::render_btn_action_quick("pen", $route_edit, $current_role == "ROLE_EDITOR", false);
                    $render .= RenderHelper::render_btn_action_quick("trash", $route_delete, $current_role == "ROLE_EDITOR", true);
                    $render .= "</div";

                    return $render;
                }
            ])

            ->createAdapter(ORMAdapter::class, [
                'entity' => EventMedia::class,
                'query' => function (QueryBuilder $builder) use ($event_id) {
                    $builder
                        ->select('media')
                        ->from(EventMedia::class, 'media')
                        ->leftJoin('media.event', 'event')
                        ->andWhere('event.id = :event_id')
                        ->setParameter('event_id', $event_id)
                        ;


                    if (!empty($sponsor_id)) {
                        $builder->andWhere("sponsor.id = :sponsor_id")->setParameter("sponsor_id", $sponsor_id);
                    }
                },
            ])

            ->handleRequest($request);

        // dump($table);

        if ($table->isCallback()) {
            // dump($table);
            return $table->getResponse();
        }

        $create_new_route     = $this->generateUrl('admin_event_media_new_by',     [ "field" => 'event', 'value' => $event_id ]);
        $edit_event_route     = $this->generateUrl('admin_event_edit',             [ "id" => $event_id ]);
        $medias_route         = $this->generateUrl('admin_event_medias_list',      [ "event_id" => $event_id ]);
        $force_no_media_route = $this->generateUrl('admin_event_force_no_media',   [ "event_id" => $event_id ]);

        return $this->render('admin/event-media/list.html.twig', [
            'datatable' => $table,
            'allow_create_new' => $current_role == "ROLE_EDITOR",
            'create_new_route'  => $create_new_route,
            'edit_event_route'  => $edit_event_route,
            'force_no_media_route'  => $force_no_media_route,
            'medias_route'  => $medias_route,
            'current_event' => $current_event,
            'user_role' => $current_role
        ]);
    }

    #[Route('/{event_id}/no-media', name: 'force_no_media', priority: 2)]
    public function no_media($event_id, Request $request, DataTableFactory $dataTableFactory, EntityManagerInterface $manager)
    {   
        if (!$this->getUser()) { return $this->redirectToRoute('auth_login');}
        if (!in_array("ROLE_EDITOR", $this->getUser()->getRoles())) throw new AccessDeniedException();

        $current_event = $manager->getRepository(Event::class)->find($event_id);

        $current_event->setForceNoMedia(true);
        $manager->flush();

        return $this->redirectToRoute('admin_event_medias_list',      ["event_id" => $event_id ]);
    }

}
