package com.sonic.frog.common;

import com.alibaba.fastjson.JSONObject;
import com.sonic.common.AppRuntime;
import com.sonic.common.client.JobmanClient;
import com.sonic.common.client.impl.JobmanClientImpl;
import com.sonic.common.log.RequestLogAspect;
import com.sonic.common.rpc.HttpClient;
import com.sonic.common.rpc.RpcClient;
import com.sonic.common.rpc.RpcClientImpl;
import com.sonic.common.stat.FrequencyAlertInterceptor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.task.TaskExecutorBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.AbstractMap;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.stream.Collectors;

import static org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME;

/**
 * @author code
 */
@Slf4j
public class GlobalConfig {
    @Value("${spring.application.name}")
    private String appName;
    @Value("${spring.application.id}")
    private String appId;

    @Bean
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor() {
        return new ScheduledThreadPoolExecutor(1);
    }

    /**
     * XXX Spring默认配置当有Executor的bean后不再装载TaskExecutor, 这里因为手动注册了
     * {@link #scheduledThreadPoolExecutor}会导致spring不再自动注册TaskExecutor, 因此需要去掉ConditionalOnMissingBean的限制.
     * 参考{@link TaskExecutionAutoConfiguration#applicationTaskExecutor}
     */
    @Bean(name = {APPLICATION_TASK_EXECUTOR_BEAN_NAME,
            AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME})
    public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
        return builder.build();
    }

    @Bean
    public RequestLogAspect requestLogAspect() {
        return new RequestLogAspect();
    }

    @Bean
    AppRuntime appRuntime(ApplicationContext applicationContext) {
        return AppRuntime.builder().appId(appId).appName(appName).applicationContext(applicationContext).build();
    }

    /**
     * 用于配置接口访问频率超限告警, 接口频率配置参考application.yml中的web.frequency-alert.rules
     * TODO 根据需要配置为输出到日志或者alertClient
     *
     * @return
     */
    @Bean
    public FrequencyAlertInterceptor frequencyAlertInterceptor(RuleConfig ruleConfig) {
        return new FrequencyAlertInterceptor(ruleConfig.getAlertRuleMap(),
                (request, frequencyAlert) -> log.warn("frequency alert, api frequency alert, url = {} alert = {}",
                        request.getRequestURI(), JSONObject.toJSONString(frequencyAlert)));
    }

    @Bean
    @Primary
    public RpcClient rpcClient() {
        return new RpcClientImpl(HttpClient.Config.EMPTY);
    }

    @Bean
    public JobmanClient jobmanClient(AppRuntime appRuntime, TaskExecutor taskExecutor, RedisTemplate<String, String> redisTemplate) {
        return new JobmanClientImpl.Builder().appRuntime(appRuntime).taskExecutor(taskExecutor).redisTemplate(redisTemplate).build();
    }

    @Data
    @Component
    @EnableConfigurationProperties
    @ConfigurationProperties(prefix = "web.frequency-alert")
    public static class RuleConfig {
        private List<String> rules;

        public Map<String, String> getAlertRuleMap() {
            if (rules == null) {
                return Collections.emptyMap();
            }
            return rules.stream()
                    .map(e -> {
                        String[] split = e.split(":");
                        return new AbstractMap.SimpleEntry<>(split[0], split[1]);
                    }).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));
        }
    }
}
