<?php
namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\HttpFoundation\Session\Session;

use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $session = new Session();
        $fields=$options["fields"];
        if(!is_array($fields)) $fields=[];

        $builder->add('submit',
            SubmitType::class, array(
                "label"       => ($options["mode"]=="delete"?"Confirmer la Suppression":"Valider"),
                "attr"        => ($options["mode"]=="delete"?array("class" => "btn btn-danger"):array("class" => "btn btn-success"))
            )
        );

         # Obligatoire
        $builder->add('username',
            TextType::class, array(
                "label"       =>"Login",
                "disabled"    => ($options["mode"]=="submit"?false:true),
                "attr"        => array("autocomplete" => "new-password")
            )
        );

        $builder->add('lastname',
            TextType::class, array(  
                "label"       =>"Nom",
                "disabled"    => ($options["mode"]=="delete"||$options["masteridentity"]!="SQL"?true:false),
            )
        );

        $builder->add('email',
            EmailType::class, array(
                "label" =>"Mail",
                "disabled" => ($options["mode"]=="delete"||$options["mode"]=="send"||$options["masteridentity"]!="SQL"?true:false),
            )
        );

        if($options["access"]=="config") {
            $choices=array("Utilisateur" => "ROLE_USER","Animateur de Groupe" => "ROLE_ANIM","Modérateur" => "ROLE_MODO","Administrateur" => "ROLE_ADMIN");
            $onfocus=($options["perm"]?"":"this.defaultIndex=this.selectedIndex;");
            $onchange=($options["perm"]?"":"this.selectedIndex=this.defaultIndex;");
            $readonly=($options["perm"]?"":" background-color: #eee;");
            $builder->add("role",
                ChoiceType::class,array(
                    "label"       =>"Rôle",
                    "attr"        => array("style" => "$readonly","onfocus" => $onfocus, "onchange" => $onchange),
                    "required"    => true,
                    "choices"     => $choices));

            $builder->add('permmodoprofil',
                EntityType::class,[
                    "class"         => "App\Entity\PermModoProfil",
                    "label"         => "Profil de Modération",
                    "choice_label"  => "name",
                    'disabled'      => ($options["mode"]=="delete"?true:false),
                    "required"      => false,
                    "attr"          => array("style" => "$readonly","onfocus" => $onfocus, "onchange" => $onchange),
                ]
            );   
            
            $builder->add('note',
                TextareaType::class, array(
                    "label"       => "Notes Administrateur",
                    "required"    => false,
                    "disabled"    => ($options["mode"]=="delete"?true:false),
                    "attr"        => array("style" => "height: 130px")
                )
            );             
        }

        $perm=$options["perm"];
        $userid=$options["userid"];
        $access=$options["access"];
        $builder->add('niveau01',
            EntityType::class,
            array("class"        => "App\Entity\Niveau01",
                  "label"        => $session->get('labelniveau01'),
                  'placeholder'  => '== Choisir '.$session->get('labelniveau01').' ==',
                  "choice_label" => "label",
                  "query_builder"=> function (EntityRepository $er) use($access,$perm,$userid) { 
                        if($access=="config") {
                            if($perm)
                                return $er->createQueryBuilder('niveau01')->orderBy('niveau01.label','ASC');
                            else {
                                $result=$er->createQueryBuilder("table")->innerJoin("App\Entity\UserModo", "usermodo", Join::WITH, "table.id = usermodo.niveau01")->orderBy('table.label','ASC');
                                $result->andWhere("usermodo.user = :userid");
                                $result->setParameter('userid', $userid);
                                return $result;
                            }
                        }
                        else {
                            return $er->createQueryBuilder('niveau01')->orderBy('niveau01.label','ASC');
                        }
                    },                  
                    "disabled"    => ($options["mode"]=="delete"||$options["masteridentity"]!="SQL"?true:false),
                    "attr"         => array("readonly" => ($options["mode"]=="delete"?true:false)))); 

                    
        $builder->add('niveau01other',
            TextType::class, array(  
                "label"       =>"Autre ".$session->get('labelniveau01'),
                "disabled"    => ($options["mode"]=="delete"?true:false),
                "required"    => false,
            )
        );

        if($options["mode"]!="delete"&&$options["masteridentity"]=="SQL") {
            $builder->add('password',
                RepeatedType::class, array(
                    "type" => PasswordType::class,
                    "required" => ($options["mode"]=="submit"?true:false),
                    "options" => array("always_empty" => true),
                    "first_options"  => array("label" => "Mot de Passe","attr" => array("autocomplete" => "new-password")),
                    "second_options" => array('label' => 'Confirmer Mot de Passe'),
                    "invalid_message" => "Mot de passe non valide"
                )
            );
        }
        
        
        
        # En fonction de datauser

        // acces jamais bloqué en config
        if($access=="config") {
            foreach($fields as $key => $field) {
                if($field["perm"]==3) $fields[$key]["perm"]=1;  
            }
        }

        if(!array_key_exists("firstname",$fields)) $fields["firstname"]["perm"]==1;
        if($fields["firstname"]["perm"]!=0) {
            $builder->add('firstname',
                TextType::class, [
                    "label"       =>"Prénom",
                    "required"    => ($fields["firstname"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$options["masteridentity"]!="SQL"||$fields["firstname"]["perm"]==3?true:false),
                ]);
        }

        if(!array_key_exists("visible",$fields)) $fields["visible"]["perm"]==2;
        if($fields["visible"]["perm"]!=0) {
            $choices=array("oui" => "1","non" => "0");
            $builder->add("visible",
                ChoiceType::class,array(
                    "label"       =>"Visible",
                    'disabled'    => ($options["mode"]=="delete"||$fields["visible"]["perm"]==3?true:false),
                    "required"    => ($fields["visible"]["perm"]==2),
                    "choices"     => $choices
                )
            );
        }

        if(!array_key_exists("usualname",$fields)) $fields["usualname"]["perm"]==1;
        if($fields["usualname"]["perm"]!=0) {
            $builder->add('usualname',
                TextType::class, array(
                    "label"       => "Nom d'Usage",
                    "required"    => ($fields["usualname"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$fields["usualname"]["perm"]==3?true:false),
                )
            ); 
        }

        if(!array_key_exists("gender",$fields)) $fields["gender"]["perm"]==1;
        if($fields["gender"]["perm"]!=0) {
            $choices=array("" => "", "homme" => "male","femme" => "female");
            $builder->add("gender",
                ChoiceType::class,array(
                    "label"       =>"Sexe",
                    "required"    => ($fields["gender"]["perm"]==2),
                    'disabled'    => ($options["mode"]=="delete"||$fields["gender"]["perm"]==3?true:false),
                    "choices"     => $choices
                )
            );
        }  

        if(!array_key_exists("givensname",$fields)) $fields["givensname"]["perm"]==1;
        if($fields["givensname"]["perm"]!=0) {
            $builder->add('givensname',
                TextType::class, array(
                    "label"       => "Autre Prénom",
                    "required"    => ($fields["givensname"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$fields["givensname"]["perm"]==3?true:false),
                )
            );  
        }

        if(!array_key_exists("telephonenumber",$fields)) $fields["telephonenumber"]["perm"]==1;
        if($fields["telephonenumber"]["perm"]!=0) {
            $builder->add('telephonenumber',
                TextType::class, array(
                    "label"       => "Téléphone",
                    "required"    => ($fields["telephonenumber"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$fields["telephonenumber"]["perm"]==3?true:false),
                )
            );  
        }

        if(!array_key_exists("postaladress",$fields)) $fields["postaladress"]["perm"]==1;
        if($fields["postaladress"]["perm"]!=0) {
            $builder->add('postaladress',
                TextareaType::class, array(
                    "label"       => "Adresse",
                    "required"    => ($fields["postaladress"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$fields["postaladress"]["perm"]==3?true:false),
                    "attr"        => array("style" => "height:90px")
                )
            );   
        }    

        if(!array_key_exists("birthdate",$fields)) $fields["birthdate"]["perm"]==1;
        if($fields["birthdate"]["perm"]!=0) {
            $builder->add('birthdate',
                DateType::class, array(
                    "label"       => "Date de Naissance",
                    "required"    => ($fields["birthdate"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$fields["birthdate"]["perm"]==3?true:false),
                    "widget"      => 'single_text',
                    "format"      => "dd/MM/yyyy",
                    "html5"       => false,
                    "attr"        => array("readonly" => ($options["mode"]=="delete"?true:false)
                    )
                )
            );
        }      

        if(!array_key_exists("birthcountry",$fields)) $fields["birthcountry"]["perm"]==1;
        if($fields["birthcountry"]["perm"]!=0) {
            $builder->add('birthcountry',
                Select2EntityType::class, array(
                    'label' => "Pays de Naissance",
                    'disabled' => ($options["mode"]=="delete"||$fields["birthcountry"]["perm"]==3?true:false),
                    "required"    => ($fields["birthcountry"]["perm"]==2),
                    'multiple' => false,
                    'remote_route' => 'app_core_ajax_country_list',
                    'class' => 'App\Entity\Country',
                    'primary_key' => 'id',
                    'text_property' => 'label',
                    'minimum_input_length' => 2,
                    'page_limit' => 10,
                    'allow_clear' => true,
                    'delay' => 250,
                    'cache' => false,
                    'cache_timeout' => 60000, // if 'cache' is true
                    'language' => 'fr',
                    'placeholder' => 'Selectionner un pays',
                )
            );
        }

        if(!array_key_exists("birthplace",$fields)) $fields["birthplace"]["perm"]==1;
        if($fields["birthcountry"]["perm"]!=0&&$fields["birthplace"]["perm"]!=0) {
            $builder->add('birthplace',
                Select2EntityType::class, array(
                    'label' => "Ville de Naissance",
                    'disabled' => ($options["mode"]=="delete"||$fields["birthplace"]["perm"]==3?true:false),
                    "required"    => false,
                    'multiple' => false,
                    'remote_route' => 'app_core_ajax_city_list',
                    'class' => 'App\Entity\City',
                    'primary_key' => 'id',
                    'text_property' => 'label',
                    'minimum_input_length' => 2,
                    'page_limit' => 10,
                    'allow_clear' => true,
                    'delay' => 250,
                    'cache' => false,
                    'cache_timeout' => 60000, // if 'cache' is true
                    'language' => 'fr',
                    'placeholder' => 'Selectionner une ville',
                )
            ); 
        }

        if(!array_key_exists("job",$fields)) $fields["job"]["perm"]==1;
        if($fields["job"]["perm"]!=0) {
            $builder->add('job',
                TextType::class, array(
                    "label"       => "Métier",
                    "required"    => ($fields["job"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$fields["job"]["perm"]==3?true:false),
                )
            );   
        }           

        
        if(!array_key_exists("position",$fields)) $fields["position"]["perm"]==1;
        if($fields["position"]["perm"]!=0) {
            $builder->add('position',
                TextType::class, array(
                    "label"       => "Fonction",
                    "required"    => ($fields["position"]["perm"]==2),
                    "disabled"    => ($options["mode"]=="delete"||$fields["position"]["perm"]==3?true:false),
                )
            );   
        } 
     
        if($session->get('viewniveau02')) {
            if(!array_key_exists("niveau02",$fields)) $fields["niveau02"]["perm"]==1;
            if($fields["niveau02"]["perm"]!=0) {
                $builder->add('niveau02',
                    Select2EntityType::class, array(
                        'label' => $session->get('labelniveau02'),
                        'disabled' => ($options["mode"]=="delete"||$fields["niveau02"]["perm"]==3?true:false),
                        "required"    => ($fields["niveau02"]["perm"]==2),
                        'multiple' => false,
                        'remote_route' => 'app_core_ajax_niveau02_list',
                        'class' => 'App\Entity\Niveau02',
                        'req_params' => ['niveau01' => 'parent.children[niveau01]'],
                        'primary_key' => 'id',
                        'text_property' => 'label',
                        'minimum_input_length' => 0,
                        'page_limit' => 10,
                        'allow_clear' => true,
                        'delay' => 250,
                        'cache' => false,
                        'cache_timeout' => 60000, // if 'cache' is true
                        'language' => 'fr',
                        'placeholder' => 'Selectionner '.$session->get('labelniveau02'),
                    )
                );         
            }
        }
        
        if($options["access"]=="config") {
            if(!array_key_exists("authlevel",$fields)) $fields["authlevel"]["perm"]==2;
            if($fields["authlevel"]["perm"]!=0) {
                $choices=array("simple" => "simple","substantiel" => "substantiel","fort" => "fort");
                $builder->add("authlevel",
                    ChoiceType::class,array(
                        "label"       =>"Niveau d'authentification",
                        "required"    => ($fields["authlevel"]["perm"]==2),
                        'disabled'    => ($options["mode"]=="delete"||$fields["authlevel"]["perm"]==3?true:false),
                        "choices"     => $choices
                    )
                );
            }

            if(!array_key_exists("belongingpopulation",$fields)) $fields["belongingpopulation"]["perm"]==2;
            if($fields["belongingpopulation"]["perm"]!=0) {
                $choices=array("agent" => "agent","prestataire" => "prestataire","partenaire" => "partenaire","stagiaire" => "stagiare");
                $builder->add("belongingpopulation",
                    ChoiceType::class,array(
                        "label"       =>"Population d'appartenance",
                        "required"    => ($fields["belongingpopulation"]["perm"]==2),
                        'disabled'    => ($options["mode"]=="delete"||$fields["belongingpopulation"]["perm"]==3?true:false),
                        "choices"     => $choices
                    )
                );
            }
        }
        
        if(!array_key_exists("visite",$fields)) $fields["visite"]["perm"]==2;
        if($fields["visite"]["perm"]!=0) {
            $builder->add('visitedate', DateTimeType::class, [
                "label"         => 'Date de dernière visite',
                "disabled"      => true,
                "required"      => ($fields["visite"]["perm"]==2),
                "widget"        => 'single_text',
            ]);

            $builder->add('visitecpt', IntegerType::class, [
                "label"         => 'Nombre de visites',
                "required"    => ($fields["visite"]["perm"]==2),
                "disabled"      => true,
            ]);
        }
        
        $builder->add('motivation',
            TextareaType::class, array(
                "label"       => "Motivation",
                "required"    => false,
                "disabled"    => ($options["mode"]=="delete"?true:false),
                "attr"        => array("style" => "height: 90px")
            )
        ); 

        # Avatar
        $builder->add('avatar',HiddenType::class, array("empty_data" => "noavatar.png"));

        # Groupes de l'utilisateur
        $builder->add('linkgroups',HiddenType::class, array("mapped" => false));

        # Modération
        $builder->add('linkmodos',HiddenType::class, array("mapped" => false));  
                
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'App\Entity\User',
            'mode' => "string",
            'access' => "string",
            'perm' => "boolean",
            'userid' => "integer",
            'masteridentity' => "string",
            "fields" => "array"
        ));
    }
}

