<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\ConnectCpCreationClient;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class ConnectFacebookInstagramIdType extends AbstractType
{

    /**
     * @var array
     */
    private $client;


    public function __construct(ConnectCpCreationClient $client)
    {
        $this->client = $client;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            [$this, 'onPreSetData']
        );
    }

    public function onPreSetData(FormEvent $event)
    {
        $form   = $event->getForm();
        $parent = $form->getParent();
        $userId = $parent->getNormData()->getId();
        if ($userId) {
            $result = $this->client->get(
                '/api/client_socials/'.$userId
            );

            $clientSocial = json_decode($result->getBody()->getContents(), true);
            $choices      = [];
            foreach ($clientSocial['dataAccounts']['data'] as $item) {
                $name       = $item['name'];
                if (array_key_exists('instagram_business_account', $item)) {
                    $instagramId = $item['instagram_business_account']['id'];
                    $choices[$name] = $instagramId;
                }

            }
            $form->getParent()->remove('accountInstagram');
            $parent->add(
                'accountInstagram', ChoiceType::class, [
                    'choices'     => $choices,
                    'required'    => false,
                    'multiple'    => false,
                    'placeholder' => 'Aucun',
                    'attr'        => [
                        'class' => 'select2',
                    ],
                ]
            );
        }
    }

    public function getParent()
    {
        return ChoiceType::class;
    }
}
