<?php

namespace Cadoles\SAMLBundle\Controller;

use LightSaml\SpBundle\Controller\DefaultController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use LightSaml\Meta\TrustOptions\TrustOptions;
use Symfony\Component\HttpFoundation\Cookie;

class DefaultController extends BaseController
{
    public function metadataAction()
    {
        return parent::metadataAction();
    }

    public function discoveryAction()
    {
        $masteridentity=$this->getParameter("masteridentity");
        if($masteridentity!="SAML") {
            return $this->render('CadolesCoreBundle:Core:reconnect.html.twig', [
                'useheader'         => true,
                'usemenu'           => false,
                'usesidebar'        => false,   
                'redirectto'        => $this->get('session')->get("_security.main.target_path")
            ]);             
        }
            
        $request = $this->container->get('request_stack')->getCurrentRequest();

        $parties = $this->get('lightsaml.container.build')->getPartyContainer()->getIdpEntityDescriptorStore()->all();

        if (count($parties) == 1) {
            return $this->redirect($this->generateUrl('lightsaml_sp.login', ['idp' => $parties[0]->getEntityID()]));
        }

        if ($request->cookies->get('idp')) {
            return $this->redirect($this->generateUrl('lightsaml_sp.login', ['idp' => $request->cookies->get('idp')]));
        }

        return $this->render('LightSamlSpBundle::discovery.html.twig', [
            'parties' => $parties,
        ]);
    }

    public function loginAction(Request $request)
    {
        $idpEntityId = $request->get('idp');

        if (null === $idpEntityId) {
            return $this->redirect($this->generateUrl($this->container->getParameter('lightsaml_sp.route.discovery')));
        }

        $profile = $this->get('ligthsaml.profile.login_factory')->get($idpEntityId);
        $context = $profile->buildContext();
        $action = $profile->buildAction();

        $trustOptions = new TrustOptions();
        $trustOptions->setSignAuthnRequest(true);
        $trustOptions->setSignAssertions(false);

        $context->getPartyEntityContext()->setTrustOptions($trustOptions);

        $action->execute($context);

        $cookie = new Cookie('idp', $idpEntityId);
        $response = $context->getHttpResponseContext()->getResponse();
        $response->headers->setCookie($cookie);

        return $response;
    }

    public function sessionsAction()
    {
        return parent::sessionsAction();
    }
}
