package com.mma.trion.marketlink.application.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

@Configuration
@EnableOAuth2Client
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    //getAccessTokenRequest and add username and password here into this
    @Autowired
    OAuth2ClientContext oauth2ClientContext;
         
    @Value("${security.oauth2.client.clientId}")
    private String clientId;

    @Value("${security.oauth2.client.clientSecret}")
    private String clientSecret;

    @Value("${security.oauth2.client.accessTokenUri}")
    private String accessTokenUri;
    
    /* Match everything without a suffix (so not a static resource) */
    /*@RequestMapping(value = "/{path:[^\\.]*}")
      public String redirect() {
        
    *//** Forward to home page so that route is preserved.
       **//*  
              return "forward:/";
              }*/
    
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http

            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/", "/login**", "/webjars/**").permitAll()
            .anyRequest().authenticated()
            .and().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
            .and().logout().logoutSuccessUrl("/").permitAll()
            .and().csrf().csrfTokenRepository(csrfTokenRepository())
            .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
            //.and().csrf().disable()
            .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
        ;

    }   
    
    
    private Filter ssoFilter() {
        CustomOAuth2ClientAuthenticationProcessingFilter customOAuth2ClientAuthenticationProcessingFilter
            = new CustomOAuth2ClientAuthenticationProcessingFilter("/login");
        this.setAuthenticationConfiguration(null);
        //OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationProcessingFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/wso2");
        
        OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(oauth2ProtectedResourceDetails(), oauth2ClientContext);
        customOAuth2ClientAuthenticationProcessingFilter.setRestTemplate(oAuth2RestTemplate);
        customOAuth2ClientAuthenticationProcessingFilter.setTokenServices(new UserInfoTokenServices(resourceServerProperties().getUserInfoUri(), oauth2ProtectedResourceDetails().getClientId()));
        return customOAuth2ClientAuthenticationProcessingFilter;
    }

    
    @Bean
    @ConfigurationProperties("security.oauth2.client")
    public OAuth2ProtectedResourceDetails oauth2ProtectedResourceDetails() {
        OAuth2ProtectedResourceDetails details = new ResourceOwnerPasswordResourceDetails();
        return details;
    }
    
    @Bean
    @ConfigurationProperties("security.oauth2.resource")
    ResourceServerProperties resourceServerProperties() {
        return new ResourceServerProperties();
    }
        
    @Bean
    public FilterRegistrationBean oauth2ClientFilterRegistration(
        CustomOAuth2ClientAuthenticationProcessingFilter filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter);
        registration.setOrder(-100);
        return registration;
    }
    
    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                            FilterChain filterChain) throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
    
    

}
