<?php

namespace App\Controller\Admin;

use App\Controller\AbstractAdminController;
use App\Entity\CollectifData\CollectifData;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use Lc\SovBundle\Generator\CsvGenerator;
use Lc\SovBundle\Repository\RepositoryQueryInterface;
use Symfony\Component\HttpFoundation\Request;

class CollectifDataCrudController extends AbstractAdminController
{
    public static function getEntityFqcn(): string
    {
        return CollectifData::class;
    }

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

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

    public function configureActions(Actions $actions): Actions
    {
        parent::configureActions($actions);

        $export = Action::new('export', 'actions.export')
                ->setIcon('fa fa-download')
                ->linkToCrudAction('exportCsv')
                ->setCssClass('btn btn-sm btn-primary export-csv')
                ->createAsGlobalAction();

        return $actions->add(Crud::PAGE_INDEX, $export);
    }

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

    public function createIndexRepositoryQuery(
        SearchDto $searchDto,
        EntityDto $entityDto,
        FieldCollection $fields,
        FilterCollection $filters
    ): RepositoryQueryInterface {
        $repositoryQuery = parent::createIndexRepositoryQuery($searchDto, $entityDto, $fields, $filters);
        $status = $searchDto->getRequest()->get('status');
        if ($status || $status == 0) {
            $repositoryQuery->filterByStatus($searchDto->getRequest()->get('status'));
        }
        return $repositoryQuery;
    }

    public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
    {
        $entityInstance->setUser($this->getUser());
        $entityManager->persist($entityInstance);
        $entityManager->flush();

        parent::persistEntity($entityManager, $entityInstance);
    }

    public function exportCsv(Request $request)
    {
        $csv = new CsvGenerator();
        $csv->enableConvertEncoding('ISO-8859-1');
        $csv->setTitle('Export_Liste_Collectif', true);

        $columns = [
                'category' => 'Catégorie',
                'thematic' => 'Thématique',
                'subthematic' => 'Contribution',
                'territory' => 'Lieu',
                'nb_participant' => 'Participants',
                'description' => 'Description'
        ];
        $csv->setColumns($columns);

        $resultArray = $this->generateAllResultArray();

        $csv = $this->generateCsvData($csv, $resultArray);

        return $csv->getReponse();
    }

    private function generateAllResultArray(): array
    {
        $dreamArray = $this->getDreamContainer()->getStore()->get();
        $revoltArray = $this->getRevoltContainer()->getStore()->get();
        $projectBoostArray = $this->getProjectBoostContainer()->getStore()->get();
        $projectInspiringArray = $this->getProjectInspiringContainer()->getStore()->get();

        return array_merge($dreamArray, $revoltArray, $projectBoostArray, $projectInspiringArray);
    }

    private function generateCsvData($csv, $resultArray)
    {
        foreach ($resultArray as $result) {
            $territory = $subthematic = $thematic = "";

            if ($result->getCollectifData()) {
                $collectifData = $result->getCollectifData();
                $territory = $collectifData->getTerritory()->getName();

                if ($result->getSubthematic()) {
                    $subthematic = $result->getSubthematic()->getName();
                }

                if ($result->getThematic()) {
                    $thematic = $result->getThematic()->getName();
                }

                $data = [
                        'category' => $result->__toString(),
                        'thematic' => $thematic,
                        'subthematic' => $subthematic,
                        'territory' => $territory,
                        'nb_participant' => $collectifData->getNbParticipant(),
                        'description' => $result->getDescription()
                ];

                $csv->row($data);
            }
        }

        return $csv;
    }
}
