package cn.ey.biz.module.system.framework.dynamic_api.config;

import cn.ey.biz.common.pojo.R;
import cn.ey.biz.module.system.framework.dynamic_api.core.AbstractResourceStorage;
import cn.ey.biz.module.system.framework.dynamic_api.core.handler.RequestHandler;
import cn.ey.biz.module.system.framework.dynamic_api.core.service.RequestDynamicRegistry;
import cn.ey.biz.module.system.framework.dynamic_api.core.util.Mapping;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@EnableConfigurationProperties(DynamicApiProperties.class)
@Configuration
public class DynamicRegistryConfiguration {

    @Autowired
    private DynamicApiProperties properties;

    @Autowired
    @Lazy
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Bean
    @ConditionalOnMissingBean
    public AbstractResourceStorage resourceStorage() {
        return new AbstractResourceStorage();
    }

    @Bean
    @ConditionalOnMissingBean
    public RequestHandler requestHandler() {
        return new RequestHandler(){
            @ResponseBody
            @Override
            public R invoke(HttpServletRequest request, HttpServletResponse response, Map<String, Object> pathVariables, Map<String, Object> defaultHeaders, Map<String, Object> parameters, Map<String, Object> requestBody) {
                return R.success(null);
            }
        };
    }

    @SneakyThrows
    @Bean
    @ConditionalOnMissingBean
    public RequestDynamicRegistry requestDynamicRegistry(AbstractResourceStorage resourceStorage, RequestHandler requestHandler) {
        return new RequestDynamicRegistry(resourceStorage,
                Mapping.create(requestMappingHandlerMapping, null),
                requestHandler,
                properties.isAllowOverride(),
                properties.getPrefix());
    }

}
