<?php

namespace Cadoles\CoreBundle\Service;

use Cadoles\CoreBundle\Entity\User;
use Doctrine\Common\Persistence\ObjectManager;
use LightSaml\Model\Protocol\Response;
use LightSaml\SpBundle\Security\User\UserCreatorInterface;
use LightSaml\SpBundle\Security\User\UsernameMapperInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class samlUserCreatorService implements UserCreatorInterface
{
    private $objectManager;
    private $container;
    protected $session;

    public function __construct($objectManager, $container, Session $session)
    {
        $this->objectManager = $objectManager;
        $this->container = $container;
        $this->session = $session;
    }

    public function createUser(Response $response)
    {
        // Masteridentity
        $masteridentity=$this->container->getParameter("masteridentity");

        $em = $this->objectManager;
        $attributeMapper = $this->container->get('cadoles.saml_attribute_mapper');
        $attributes = $attributeMapper->getAttributesFromResponse($response);
        
        $username   = (array_key_exists($this->container->getParameter('user_attr_saml_username'),$attributes)?$attributes[$this->container->getParameter('user_attr_saml_username')]:null);
        $email      = (array_key_exists($this->container->getParameter('user_attr_saml_mail'),$attributes)?$attributes[$this->container->getParameter('user_attr_saml_mail')]:null);
        $lastname   = (array_key_exists($this->container->getParameter('user_attr_saml_lastname'),$attributes)?$attributes[$this->container->getParameter('user_attr_saml_lastname')]:null);
        $firstname  = (array_key_exists($this->container->getParameter('user_attr_saml_firstname'),$attributes)?$attributes[$this->container->getParameter('user_attr_saml_firstname')]:null);

        // Username obligatoire
        if(is_null($username))
            throw new NotFoundHttpException('Permission denied. No Username mapped');

        // On cherche l'utilisateur
        $user = $em->getRepository('CadolesCoreBundle:User')->findOneByUsername($username);
        if (!$user) {
            if($masteridentity=="SQL") {
                // C'est pas normal que l'on puisse se connecter alors que l'utilisateur n'est pas connu en base
                // La base étant le maitre de l'identité
                throw new NotFoundHttpException('Permission denied');
            }

            if($masteridentity=="LDAP") {
                // Normalement la synchronisation des comptes aurait du générer le compte en base c'est donc pas normal
                // Peut-être juste relancer une synchronisation
                throw new NotFoundHttpException('Permission denied. Need to synchronize LDAP ? Contact your administrator');
            }

            if($masteridentity=="SSO") {

                // On calcule le niveau01 de l'utilisateur
                $niveau01=$em->getRepository('CadolesCoreBundle:Niveau01')->calculateNiveau01($attributes);
                if(!$niveau01)
                    throw new NotFoundHttpException('Permission denied. No Organisation Niveau 01 match');

                // Là c'est normal que potentiellement il n'existe pas il faut donc l'autogénérer
                $user = new User();
                $user->setUsername($username);
                $user->setEmail($email);
                $user->setLastname($lastname);
                $user->setFirstname($firstname);

                $user->setPassword("SAMLPWD-".$username);
                $user->setSalt("SAMLPWD-".$username);
                
                $user->setNiveau01($niveau01);
                $user->setSiren($niveau01->getSiren());
                $user->setSiret("");

                $user->setAvatar("noavatar.png");
                $user->setVisible(true);
                $user->setAuthlevel("simple");
                $user->setBelongingpopulation("agent");
                $user->setRole("ROLE_USER");

                // Création
                $em->persist($user);
                $em->flush();

                // On calcule les groupes de l'utilisateur
                $user=$groups=$em->getRepository('CadolesCoreBundle:Group')->calculateGroup($user,$attributes);                
            }
        }    

        // Sauvegarde des attributes en session
        $this->session->set('attributes', $attributes);

        return $user;
    }
}
