package com.crm.manager.configuration;

import com.crm.login.rely.backend.property.LoginConfigureProperty;
import com.crm.manager.interceptor.RoleInterceptor;
import com.crm.manager.property.RoleConfigureProperty;
import com.crm.manager.service.UserRoleService;
import com.crm.rely.backend.aspect.ControllerAop;
import com.crm.rely.backend.service.RedisService;
import com.google.common.base.Strings;
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.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

@Configuration
@Order(3)
public class InterceptorRoleConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    LoginConfigureProperty loginConfigureProperty;
    @Autowired
    RoleConfigureProperty roleConfigureProperty;

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserRoleService roleInfoService;

    @Autowired
    private ControllerAop controllerAop;
    @Value("${role.googleVerified:false}")
    private boolean googleVerified;

    @Bean
    RoleInterceptor loginInterceptor() {
        return new RoleInterceptor(redisService, roleInfoService, controllerAop, googleVerified);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> stringList = new ArrayList<String>();
        for (String value : loginConfigureProperty.getExcludePathPatterns()) {
            stringList.add(value);
        }
        for (String value : roleConfigureProperty.getExcludePathPatterns()) {
            if (!Strings.isNullOrEmpty(value)) {
                stringList.add(value);
            }
        }
        String[] excludeList = new String[stringList.size()];

        stringList.toArray(excludeList);

        registry.addInterceptor(new RoleInterceptor(redisService, roleInfoService, controllerAop, googleVerified)).addPathPatterns("/**").excludePathPatterns(excludeList);
        super.addInterceptors(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("POST").maxAge(3600);
        super.addCorsMappings(registry);
    }
}