package com.jsc.oscm.security;

import com.alibaba.fastjson.JSON;
import com.jsc.oscm.model.ReturnT;
import com.jsc.oscm.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.header.HeaderWriter;
import org.springframework.security.web.header.HeaderWriterFilter;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyAuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    MyAuthenticationFailHandler authenticationFailHandler;

    @Autowired
    MyUserDetailService myUserDetailService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//		auth.inMemoryAuthentication()
//		.passwordEncoder(new BCryptPasswordEncoder())
//		.withUser("admin")
//		.password(new BCryptPasswordEncoder().encode("1111111111"))
//		.roles("admin");
        auth.userDetailsService(myUserDetailService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<HeaderWriter> headerWriters = new ArrayList<>();
        headerWriters.add(new MyHeaderWriter());
        http
                .csrf().disable()
                .authorizeRequests(authorizeRequests -> authorizeRequests
                        .antMatchers("/login/**").permitAll()//url不需要api前缀
                        .antMatchers("/resources/**").permitAll()
                        .antMatchers("/open/**").permitAll()
                        .antMatchers("/website/**").permitAll()
                        .antMatchers("/metadict/**").permitAll()
                        .antMatchers("/metadata/**").permitAll()
                        .antMatchers("/target/api/**","/rules/api/**").permitAll()
                        .antMatchers("/rules/parser/**").permitAll()
                        .anyRequest().authenticated())
                .addFilter(new HeaderWriterFilter(headerWriters))
                .formLogin()
                .successHandler(authenticationSuccessHandler).failureHandler(authenticationFailHandler)
                .and().logout()
                .logoutSuccessHandler((request, response, authentication) -> {
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter out = response.getWriter();
                    ReturnT<String> returnT = new ReturnT<>(200, "", "退出成功");
                    out.write(JSON.toJSONString(returnT));
                    out.flush();
                    out.close();
                })
                .and().exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter out = response.getWriter();
                    ReturnT<String> returnT = new ReturnT<>(401, "请登录", "");
                    out.write(JSON.toJSONString(returnT));
                    out.flush();
                    out.close();
                });
    }

//	@Autowired
//	TokenUserDetailService tokenUserDetailService;
//	
//	@Autowired
//	TokenManager tokenManager;
//	
//	@Override
//	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//		// TODO Auto-generated method stub
//		auth.userDetailsService(tokenUserDetailService)
//		.passwordEncoder(new BCryptPasswordEncoder());
//	}
//
//	@Override
//	protected void configure(HttpSecurity http) throws Exception {
//		// TODO Auto-generated method stub
//		http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint()).and().csrf().disable()
//		.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/public/**").permitAll()
//		.anyRequest().authenticated().and().logout().logoutUrl("/logout")
//		.addLogoutHandler(new TokenLogoutHandler(tokenManager)).and()
//		.addFilter(new TokenLoginFilter(authenticationManager(), tokenManager))
//		.addFilter(new TokenAuthenticationFilter(authenticationManager(),tokenManager)).httpBasic();
//	}


}
