/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.chushang.common.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.chushang.common.mybatis.config.MybatisPlusMapperRefresh;
import com.chushang.common.mybatis.config.MybatisPlusMetaObjectHandler;
import com.chushang.common.mybatis.resolver.SqlFilterArgumentResolver;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lengleng
 * @date 2020-03-14
 * <p>
 * mybatis plus 统一配置
 */
@Configuration(proxyBeanMethods = false)
public class PluginAutoConfiguration {

	@Autowired
	MybatisPlusProperties mybatisPlusProperties;
	@Value("${mybatis-plus.global-config.refresh.enable:false}")
	private boolean refreshMapper;

	@Bean
	public MybatisPlusMapperRefresh mybatisPlusMapperRefresh(ApplicationContext applicationContext, SqlSessionFactory sqlSessionFactory){
		Set<Resource> mapperLocations = new LinkedHashSet<>();
		for (String xx : mybatisPlusProperties.getMapperLocations()) {
			try {
				mapperLocations.addAll(Arrays.asList(applicationContext.getResources(xx)));
			} catch (Exception ignored) {
			}
		}
		return new MybatisPlusMapperRefresh(mapperLocations.toArray(new Resource[mapperLocations.size()]),
				sqlSessionFactory,
				10,
				5, refreshMapper);
	}

}
