package com.hs.admin.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Component;
import org.sqlite.JDBC;
import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author xieheng
 */
@Component
@Order(0)
public class SqliteConfig {
    @Value("${sqlite.url}")
    private String url;

    /**
     * @description:自动创建admin.db数据库文件并执行sql初始化表结构
     * @author: XieHeng
     * @return: SQLiteDataSource
     * @date: 2021/5/30 10:15 上午
     */
    @Bean
    public SQLiteDataSource getDataSource() {
        File file = new File(url);
        if (!file.exists()) {
            file.mkdirs();
        }
        SQLiteDataSource dataSource = new SQLiteDataSource();
        dataSource.setUrl("jdbc:sqlite:" + url + "admin.db?date_string_format=yyyy-MM-dd HH:mm:ss");
        Connection connection = null;
        try {
            Class.forName("org.sqlite.JDBC");
            Resource classPathResource = new ClassPathResource("main.sql");
            connection = dataSource.getConnection();
            ScriptUtils.executeSqlScript(connection, classPathResource);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (!connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return dataSource;
    }
}
