package mx.gob.jumapacelaya.controller;

import com.vaadin.flow.spring.security.VaadinWebSecurity;
import mx.gob.jumapacelaya.ui.login.LoginView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.ldap.core.support.LdapContextSource;

@EnableWebSecurity
@Configuration
public class SecurityConfiguration  extends VaadinWebSecurity {


    @Value("${spring.ldap.domain}")
    private String ldapDomain;

    @Value("${spring.ldap.urls}")
    private String ldapUrls;

    @Value("${spring.ldap.url}")
    private String ldapUrl;

    @Value("${spring.ldap.base}")
    private String ldapBase;

    @Value("${spring.ldap.password}")
    private String ldapPassword;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(
                        AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/icons/*.png"),
                        AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/images/*.png")
                ).permitAll()
                .requestMatchers(
                        AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/login*")
                ).permitAll()

        );

        super.configure(http);
        setLoginView(http, LoginView.class);
    }


   // !Esta es la real autenticacion con ldap
   @Autowired
   public void  configure(AuthenticationManagerBuilder auth) throws Exception {
       ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(ldapDomain, ldapUrl);
       provider.setConvertSubErrorCodesToExceptions(true);
       provider.setUseAuthenticationRequestCredentials(true);
       auth.authenticationProvider(provider);
   }


    @Bean
    public LdapContextSource ldapContextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(ldapUrls);
        contextSource.setBase(ldapBase);
        contextSource.setUserDn("administrator");
        contextSource.setPassword(ldapPassword);
        contextSource.setPooled(true);
        contextSource.setReferral("follow");
        return contextSource;
    }

}
