<?php

namespace Cadoles\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\Response;

use Cadoles\CoreBundle\Entity\User;
use Cadoles\CoreBundle\Form\LoginType;

class SecurityController extends Controller
{
    public function loginAction(Request $request)
    {

        $targetpath=$request->getSession()->get("_security.main.target_path");

        // Mode d'authentification
        $modeauth=$this->getParameter('mode_auth');

        switch($modeauth) {
            case "SQL":            
                $authUtils = $this->get('security.authentication_utils');

                // get the login error if there is one
                $error = $authUtils->getLastAuthenticationError();

                // last username entered by the user
                $lastUsername = $authUtils->getLastUsername();
                
                return $this->render('CadolesCoreBundle:Security:login.html.twig', array(
                    'useheader'         => false,
                    'usemenu'           => false,
                    'usesidebar'        => false,                       
                    'last_username'     => $lastUsername,
                    'error'             => $error
                ));
            break;

            case "LDAP":
           
                $authUtils = $this->get('security.authentication_utils');

                // last username entered by the user
                $lastUsername = $authUtils->getLastUsername();
                $error = "";

                // Création du formulaire
                $form = $this->createForm(LoginType::class);
                $form->handleRequest($request);

                if ($form->get('submit')->isClicked()) {
                    $data = $form->getData();
                    
                    $ldap_host      = $this->getParameter("ldap_host");
                    $ldap_port      = $this->getParameter("ldap_port");
                    $ldap_user      = $this->getParameter("ldap_user");
                    $ldap_password  = $this->getParameter("ldap_password");
                    $ldap_basedn        = $this->container->getParameter('ldap_basedn');

                    $ldapConn = ldap_connect($ldap_host, $ldap_port);
                    $fglogin = false;
                    if($ldapConn){
                        // Connexion au serveur LDAP superuser
                        @$ldapbind = ldap_bind($ldapConn, $ldap_user, $ldap_password);
                        if($ldapbind) {
                            $result = ldap_search($ldapConn, $ldap_basedn, "uid=".$data["_username"]);
                            if($result) {
                                $first = ldap_first_entry($ldapConn, $result);
                                $dn = ldap_get_dn($ldapConn, $first);       

                                @$ldapbind = ldap_bind($ldapConn, $dn, $data["_password"]);
                                if($ldapbind) {
                                    $fglogin = true;
                                }
                            }
                        }
                    }
                    
                    $em = $this->getDoctrine()->getManager();
                    $user=$em->getRepository("CadolesCoreBundle:User")->findOneBy(["username"=>$data["_username"]]);
                    if(!$user) $fglogin = false;

                    if(!$fglogin) $error = "connexion impossible";
                    else {
                        // Autoconnexion
                        // Récupérer le token de l'utilisateur
                        $token = new UsernamePasswordToken($user, null, "main", $user->getRoles());
                        $this->get("security.token_storage")->setToken($token);

                        // Simuler l'evenement de connexion
                        $event = new InteractiveLoginEvent($request, $token);
                        $dispatcher = new EventDispatcher();
                        $dispatcher->dispatch("security.interactive_login", $event);


                        return $this->redirect($this->generateUrl('cadoles_core_home'));                        
                    }
                }

                return $this->render('CadolesCoreBundle:Security:loginldap.html.twig', array(
                    'useheader'         => false,
                    'usemenu'           => false,
                    'usesidebar'        => false,
                    'last_username'     => $lastUsername,
                    'error'             => $error,
                    'form'              => $form->createView()
                ));                
            break;
        }
    }

    public function logoutAction(Request $request)
    {
        $this->get('security.context')->setToken(null);
        $this->get('request')->getSession()->invalidate();
    }

    public function killAction(Request $request)
    {
        $session = new Session();
        if($this->getParameter("auth_mode")=="SAML") {
            $samlLogout = $this->getParameter("saml_logout_url");
            return $this->redirect($samlLogout);
        }
        else
            return $this->redirectToRoute("myapp_webzine_home");
    }


    public function checkuserAction(Request $request) 
    {
        $userapp = $this->getUser();
        $fgforceconnect = $this->get('session')->get('fgforceconnect');
        $modeauth=$this->getParameter('mode_auth');

        if(is_null($userapp) && $fgforceconnect) {
            switch($modeauth) {
                case "SAML":
                    return new Response("<script>window.location.href='".$this->generateUrl("lightsaml_sp.login")."';</script>");
                break;

                case "CAS":
                    return new Response("<script>window.location.href='".$this->generateUrl("cas_sp.login")."';</script>");
                break;
                
                case "SQL":
                    return new Response("<script>window.location.href='".$this->generateUrl("cadoles_core_login")."';</script>");
                break;
                
                case "LDAP":
                    return new Response("<script>window.location.href='".$this->generateUrl("cadoles_core_ldap_login")."';</script>");
                break;
            }
        }
        else 
        {
            // Mode d'authentification
            switch($modeauth) {
                case "CAS":
                    // Init Client CAS
                    \phpCAS::setDebug(false);
                    @\phpCAS::client(CAS_VERSION_2_0, $this->container->getParameter('cas_host'), $this->container->getParameter('cas_port'), is_null($this->container->getParameter('cas_path')) ? '' : $this->container->getParameter('cas_path'), false);
                    \phpCAS::setNoCasServerValidation();
                    
                    if(\phpCAS::checkAuthentication()) {
                        $usercas = \phpCAS::getUser();
                        

                        // si on a un usercas mais pas de userapp c'est qu'il faut s'autoconnect
                        if(!$userapp) {
                            $url=$this->generateUrl('cas_sp.login');
                            return new Response(
                                '<script>document.location.replace("'.$url.'");</script>'
                            );

                        }
                    } 
                break;
            }
        }

        return new Response();
    }

    public function redirectAction($route,$id,Request $request) {
        if($route=="cadoles_core_home")
            return $this->redirectToRoute($route,["id"=>$id]);
        else 
            return $this->redirectToRoute("cadoles_core_home",["gotoroute"=>$route,"gotoid"=>$id]);
    }
}
