<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CustomFieldsBundle\Form\DataTransformer;

use Chill\CustomFieldsBundle\Entity\CustomField;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;

/**
 * Not in use ? Deprecated ?
 */
class JsonCustomFieldToArrayTransformer implements DataTransformerInterface
{
    private readonly array $customField;

    public function __construct(private readonly ObjectManager $om)
    {
        $customFields = $this->om
            ->getRepository(CustomField::class)
            ->findAll();

        // @TODO: in the array_map callback, CustomField::getLabel() does not exist. What do we do here?
        $customFieldsLablels = array_map(
            static fn ($e) => $e->getLabel(),
            $customFields
        );

        $customFieldsByLabel = array_combine($customFieldsLablels, $customFields);

        $this->customField = $customFieldsByLabel;
    }

    public function reverseTransform($customFieldsArray)
    {
        /*
        echo "<br> - - 7 - <br>";


        var_dump(array_keys($customFieldsArray));

        echo "<br> - - 8 - <br>";

        var_dump(array_keys($this->customField));

        echo "<br> - - 9 - <br>";
         */

        // var_dump($customFieldsArray);

        $customFieldsArrayRet = [];

        foreach ($customFieldsArray as $key => $value) {
            $traited = false;

            if (\array_key_exists($key, $this->customField)) {
                $type = $this->customField[$key]->getType();

                if (str_starts_with((string) $type, 'ManyToOne')) {
                    // pour le manytoone() faire
                    // un update du form en js ? : http://symfony.com/fr/doc/current/cookbook/form/form_collections.html
                    //
                    // $entityClass = substr($type, 10, -1);
                    // echo $entityClasss;
                    if (str_starts_with((string) $type, 'ManyToOnePersist')) {
                        // PEUT ETRE A FAIRE SI SEULEMENT $value->getId() ne renvoie rien...
                        //
                        //
                        $this->om->persist($value); // pas bon ici
                        // LE PERSIST NE SERT QUE LA PREMIERE FOIS
                        // plutot le mettre dans une var temporaire de adress
                        // et faire le persist qd fait sur l'obj parent
                        // regarder : http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html
                        // ou : http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
                        // dans yml :
                        //  lifecycleCallbacks:
                        //  prePersist: [ doStuffOnPrePersist, doOtherStuffOnPrePersist ]
                        $this->om->flush(); // sinon l'id pose pbm
                    }

                    $customFieldsArrayRet[$key] = $value->getId();
                    $traited = true;
                }
            }

            if (!$traited) {
                $customFieldsArrayRet[$key] = $value;
            }
        }

        // echo json_encode($customFieldsArrayRet);

        return json_encode($customFieldsArrayRet, \JSON_THROW_ON_ERROR);
    }

    public function transform($customFieldsJSON)
    {
        echo $customFieldsJSON;

        if (null === $customFieldsJSON) {
            $customFieldsArray = [];
        } else {
            $customFieldsArray = json_decode((string) $customFieldsJSON, true, 512, \JSON_THROW_ON_ERROR);
        }

        $customFieldsArrayRet = [];

        foreach ($customFieldsArray as $key => $value) {
            $traited = false;

            if (\array_key_exists($key, $this->customField)) {
                $type = $this->customField[$key]->getType();

                if (str_starts_with((string) $type, 'ManyToOne')) {
                    if (str_starts_with((string) $type, 'ManyToOnePersist')) {
                        $entityClass = substr((string) $type, 17, -1);
                    } else {
                        $entityClass = substr((string) $type, 10, -1);
                    }

                    $customFieldsArrayRet[$key] = $this->om
                        ->getRepository('ChillCustomFieldsBundle:'.$entityClass)
                        ->findOneById($value);
                    $traited = true;
                } elseif ('ManyToMany(Adress)' === $type) {
                    $customFieldsArrayRet[$key] = $value;
                }
            }

            if (!$traited) {
                $customFieldsArrayRet[$key] = $value;
            }
        }

        var_dump($customFieldsArrayRet);

        return $customFieldsArrayRet;
    }
}
