<?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 samlUserMapperService implements UsernameMapperInterface
{
    private $objectManager;
    private $container;
    protected $session;

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

    public function getUsername(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);
        
        // Normalement à ce stade l'utilisateur existe quoi qu'il arrive
        if ($user) {      

            // 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');

            // On s'assure que le niveau 02 appartient bien au niveau 01 calculé
            $sameniveau01=(!is_null($user->getNiveau02())&&$niveau01==$user->getNiveau02()->getNiveau01());

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

            // Mise à jour de l'utilisateur
            $user->setLastname($lastname);
            $user->setFirstname($firstname);
            $user->setEmail($email);
            $user->setNiveau01($niveau01);
            if(!$sameniveau01) $user->setNiveau02(null);
    
            // Sauvegarde des attributes en session
            $this->session->set('attributes', $attributes);

            // Modification de l'utilisateur
            $em->persist($user);
            $em->flush();              
            return $username;
        }
        else    
            return null;

        
    }  
}
