<?php

namespace App\Controller\Admin;

use App\Entity\User;
use App\Entity\Event;
use App\Utils\RenderHelper;
use Doctrine\ORM\QueryBuilder;
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\DateTimeColumn;
use Omines\DataTablesBundle\Column\TwigStringColumn;
use Symfony\Contracts\Translation\TranslatorInterface;
use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

#[Route("/admin/events", name: "admin_events_")]
class EventsController extends AbstractController
{

    const SESSION_FIELD = "events_list_from_field";
    const SESSION_VALUE = "events_list_from_value";


    #[Route('/', name: 'list')]
    public function list(Request $request, DataTableFactory $dataTableFactory, TranslatorInterface $t, SessionInterface $session)
    {
        return $this->__list("", "", $request, $dataTableFactory, $t, $session);
    }

    protected function getUser() : User {
        return parent::getUser();
    }

    #[Route('/{field}/{value}',
            name: 'list_by',
            requirements:[
                "field" => "partner",
                "value" => "\d+|my"
            ])]
    public function list_by(Request $request, DataTableFactory $dataTableFactory, TranslatorInterface $t, SessionInterface $session, string $field = "", string $value = "")
    {
        return $this->__list($field, $value, $request, $dataTableFactory, $t, $session);
    }


    private function __list(string $field, string $value, Request $request, DataTableFactory $dataTableFactory, TranslatorInterface $t, SessionInterface $session)
    {
        if (!$this->getUser()) { return $this->redirectToRoute('auth_login');}
        if (!in_array("ROLE_EDITOR", $this->getUser()->getRoles())) throw new AccessDeniedException();

        $is_admin = (in_array("ROLE_ADMIN", $this->getUser()->getRoles()));


        $t_root = "admin.event";
        $user = $this->getUser();

        $sponsor_id = "";

        switch ($field) {
            case 'partner':
                if ($value == "my") {
                    $sponsor_id = $this->getUser()->getSponsor()->getId();
                } else {
                    $sponsor_id = $value;
                }
                break;
            
            default:
                # code...
                break;
        }

        $table = $dataTableFactory->create()

            ->setTranslationDomain('admin')

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

            ->add('status', TwigStringColumn::class, [
                'label' => "$t_root.fields.status",
                'className' => 'status',
                'template' => '<img src="{{ asset(\'build/img/icon/admin-event-status-\' ~ row.status.value ~\'.png\') }}" alt="{{row.status.name}}" />',
            ])

            ->add('title', TextColumn::class, ['label' => "$t_root.fields.title", 'className' => 'bold'])

            ->add('imgPresentationFileName', TwigStringColumn::class, [
                'label' => "$t_root.fields.presentation",
                'className' => 'event-presentation',
                'template' => '<twig:ImageOrVideo entity="{{ row }}" imageFileNameField="imgPresentationFileName" imageFileField="imgPresentationFile" videoField="videoPresentation" alt="{{ row.title }}" filter="admin_event_list_filter" />',
            ])

            ->add('sponsors', TwigColumn::class, [
                'label' => "$t_root.fields.sponsor",
                'className' => 'sponsors-logo',
                'template' => 'admin\event\list-fields\sponsors.html.twig',
            ])

            // ->add('dump', TwigStringColumn::class, ['template' => '{{ dump(row) }}'])

            ->add('dates', TwigColumn::class, [
                'label' => "$t_root.fields.dates",
                'className' => 'event-dates',
                'template' => 'admin\event\list-fields\dates.html.twig',
            ])

            ->add('first_date', DateTimeColumn::class, ['visible' => false]) //, 'template' => "{{ value|format_datetime(locale='fr', pattern='dd MMMM yyyy HH:mm') }}"])
            ->add('last_date', DateTimeColumn::class, ['visible' => false]) //, 'template' => "{{ value|format_datetime(locale='fr', pattern='dd MMMM yyyy HH:mm') }}"])
            ->addOrderBy('first_date', \Omines\DataTablesBundle\DataTable::SORT_DESCENDING)

            ->add('type', TextColumn::class, [
                'label' => "$t_root.fields.type",
                'className' => 'type',
                'render' => function($value, $context) {
                    return $context->getType()->getName();
                }
            ])

            ->add('performers', TwigColumn::class,
                ['label' => "$t_root.fields.performers",
                'className' => 'event-performers',
                'template' => 'admin\event\list-fields\performers.html.twig'
                ]
            )

            ->add('medias', TextColumn::class,
                 ['label' => "$t_root.fields.media",
                 'className' => 'list-count',
                 'render' => function($value, $context) {

                    $count = $context->getMedias()->count();

                    $route_list = $this->generateUrl("admin_event_medias_list", ['event_id' => $context->getId()]);
                    return RenderHelper::render_linked_list($count, "images", $route_list);
                }],
            )

            ->add('active', BoolColumn::class, ['label' => "$t_root.fields.active",
                'trueValue' => '<span class="badge bg-success"><i class="fa fa-check"></i>&nbsp;' . $t->trans('active.true', domain: 'fields') . '</span>',
                'falseValue' => '<span class="badge bg-danger"><i class="fa fa-ban"></i>&nbsp;' . $t->trans('active.false', domain: 'fields') . '</span>',
                'nullValue' => 'unknown'
            ])

            ->add('actions', TextColumn::class, ['label' => '',
                'className' => 'col-actions',
                'render' => function($r_value, $context) use ($t, $t_root, $user) {

                    $route = $this->generateUrl('admin_event_edit', ["id" => $context->getId()]);
                    return RenderHelper::render_btn_action("pen", $t->trans("$t_root.actions.edit", domain: 'admin'), $route, $context->getRealRoleForUser($user) == "ROLE_EDITOR");
                }
            ])

            ->createAdapter(ORMAdapter::class, [
                'entity' => Event::class,
                'query' => function (QueryBuilder $builder) use ($sponsor_id) {
                    $builder
                        ->select('event')
                        ->addSelect('typeevent')
                        ->from(event::class, 'event')
                        ->innerJoin('event.type', 'typeevent')
                        ;

                    if (!empty($sponsor_id)) {
                        $builder
                            ->distinct()->innerJoin('event.sponsors', 'sponsors')
                            ->andWhere("sponsors.sponsor = :sponsor_id")
                            ->setParameter("sponsor_id", $sponsor_id)
                        ;
                    }
                },
            ])
            ->handleRequest($request);

        // dump($table);

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

        if (!$is_admin) {
            $create_new_route = $this->generateUrl('admin_event_new_by', ["field" => "partner", "value" => "my"]);
        } else {
            if ($field != "") {
                $create_new_route = $this->generateUrl('admin_event_new_by', ["field" => $field, "value" => $value]);
            } else {
                $create_new_route = $this->generateUrl('admin_event_new');
            }
        }

        $session->set(EventsController::SESSION_FIELD, $field);
        $session->set(EventsController::SESSION_VALUE, $value);

        return $this->render('admin/event/list.html.twig', [
            'datatable' => $table,
            'sponsor_id' => $sponsor_id,
            'allow_create_new' => true,
            'create_new_route'  => $create_new_route
        ]);
    }

    #[Route('/auto', name: 'auto_redirect', priority: 2)]
    public function auto(SessionInterface $session)
    {
        // on redirige vers la liste
        $from_field = $session->get(EventsController::SESSION_FIELD);
        $from_value = $session->get(EventsController::SESSION_VALUE);

        // on redirige vers la liste
        if ($from_field != "") {
            return $this->redirectToRoute("admin_events_list_by", ["field" => $from_field, "value" => $from_value]);
        } else {
            return $this->redirectToRoute("admin_events_list");
        }
    }


}
