package com.zhiqiyun.open.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zhiqiyun.open.Application;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class BeanConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor innerInterceptor = new PaginationInnerInterceptor();
        innerInterceptor.setDbType(DbType.MYSQL);
        innerInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(innerInterceptor);
        return interceptor;
    }

    @Bean
    public OkHttpClient okHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(30, TimeUnit.SECONDS);
        return builder.build();
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseGeneratedKeys(true);
    }

    @Bean
    public DbSearcher dbSearcher() throws Exception {
        DbConfig config = new DbConfig();
        InputStream inStream = Application.class.getResourceAsStream("/ip2region.db");
        byte[] buff = new byte[1024];
        ByteArrayOutputStream o = new ByteArrayOutputStream();
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 1024)) > 0) {
            o.write(buff, 0, rc);
        }
        byte[] in2b = o.toByteArray();
        return new org.lionsoul.ip2region.DbSearcher(config, in2b);
    }
}
