<?php
namespace Modules\Catalogue\Controller;

use Entity\Model\AutrFich;
use Entity\Model\CataBulk;
use Entity\Model\CatCaracInfo;
use Entity\Model\CCataSrc;
use Entity\Model\Grpfou;
use Entity\Model\MultiTranscod;
use Entity\Model\ParamChg;
use Entity\Model\RGamCat;
use Entity\Model\RQteCat;
use Entity\Model\StruCata;
use Entity\Model\VersCata;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Session\ParseBase1;
use Modules\Catalogue\Repository\CatalogueExterneRepository;
use Modules\Catalogue\Repository\ChargementRepository;
use Modules\Catalogue\Repository\FormatRepository;
use Modules\Catalogue\Repository\UpdateFieldCatabulkRepository;
use Modules\Catalogue\Service\ChargementCatalogueService;
use Modules\Catalogue\Service\ChargementRemiseService;
use Skeleton\Controller\Controller;

class ChargementCatalogueController extends Controller
{
    public function assistantAction():string
    {
        $idVersion = $this->request->getAttribute('idVersion');
        
        return $this->renderer->render('@catalogue/GestionVersion/popupModeAssistant', [
            'idVersion' => $idVersion,
        ]);
    }

    public function chargementAction():string|Response
    {
        $idVersion = $this->request->getAttribute('idVersion');
        $trad = $this->getTranslationService();
        $post = $this->request->getParsedBody();

        $chargementCatalogue = new ChargementCatalogueService(
            $this->pdo,
            $this->pdoStorage,
            new ParseBase1(),
            new CatalogueExterneRepository($this->pdo),
            new FormatRepository($this->pdo),
            new ParamChg($this->pdo),
            new CataBulk($this->pdo),
            new CCataSrc($this->pdo),
            new ChargementRepository($this->pdo),
            new Grpfou($this->pdo),
            new UpdateFieldCatabulkRepository($this->pdo),
            new MultiTranscod($this->pdo),
            new CatCaracInfo($this->pdo),
            new RQteCat($this->pdo),
            new ChargementRemiseService(
                new AutrFich($this->pdo),
                new VersCata($this->pdo),
                new RGamCat($this->pdo)
            )
        );
        
        if (isset($post['modeAssistant'])) {
            $chargementCatalogue->setModeAssistant(true, $post['nombreArticle']);
        }
        $chargementCatalogue->setVersion($idVersion);
        $chargementCatalogue->chargement();

        if ($chargementCatalogue->getFileMissing()) {
            $message = $trad->t('Fichier :')."<br />";
            $message .= implode("<br />", $chargementCatalogue->getFileMissing());
            $message .= "<br />".$trad->t('Le(s) fichier(s) indiqué n\'existe(s) pas.');

            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $message,
                'desactiveRow' => true,
            ]));
        } else {
            if (isset($post['modeAssistant'])) {
                $post = [
                    'listeErreur' => (isset($post['controleReferentiel']) && $post['controleReferentiel'] == 'on')? $chargementCatalogue->getAssistantError():[],
                    'nombreLignes' => $post['nombreArticle']
                ];

                return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Catalogue.ChargementCatalogue.visualisationModeAssistant'), 'post' => $post]));
            } else {
                return '';//todo a voir pour mettre en place mercure
            }
        }
    }

    public function visualisationModeAssistantAction():string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $listeErreur = $post['listeErreur'];

        $listeArticle   = (new CataBulk($this->pdo))->fetchAll([], $post);
        $struCata       = (new StruCata($this->pdo))->structWithOutTab();

        ariane::generate(2, $trad->t('Tableau de contrôle'));

        $errorByLigne = [];
        foreach ($listeErreur as $error) {
            $errorByLigne[$error['LIGNE']][$error['FIELD']] = $error['VALUE'];
        }

        return $this->renderer->render('@catalogue/GestionVersion/modeAssistant', [
            'nombreLignes'  => $post['nombreLignes'],
            'struCata'      => $struCata,
            'listeArticle'  => $listeArticle,
            'errorByLigne'  => $errorByLigne,
        ]);
    }


    public function deleteAction():response
    {
        $idVersion      = $this->request->getAttribute('idVersion');
        $idOrdre        = $this->request->getAttribute('noOrdre');

        (new ParamChg($this->pdo))->delete([
            'IDVERSION' => $idVersion,
            'ORDRE'     => $idOrdre
        ]);

        (new AutrFich($this->pdo))->delete([
            'IDVERSION'     => $idVersion,
            'ORDRE'         => $idOrdre,
        ]);

        return new response(200, [], (string) json_encode(['path' => $this->router->generateUri('Catalogue.VersionCataExterne.ajaxDetailVersion', ['idVersion' => $idVersion])]));
    }
}
