package org.ros.chatto.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Configuration
@Component

// @ConfigurationProperties(prefix = "chatto.datasource")
@Getter
// @Setter
@Slf4j
public class DataSourceConfig {

    // jdbc:mysql://localhost:3306/chatto_db?useSSL=false
    private final String DATASOURCE_URL = "jdbc:mysql://%s:%d/%s?%s";

    private final String username;
    private final String password;
    private final String databaseName;
    private final String url;
    private final int port;
    private final String params;

    public DataSourceConfig(@Value("${chatto.datasource.username}") String username,
            @Value("${chatto.datasource.password}") String password,
            @Value("${chatto.datasource.database-name}") String databaseName,
            @Value("${chatto.datasource.url}") String url, @Value("${chatto.datasource.port}") int port,
            @Value("${chatto.datasource.params}") String params) {
        this.username = username;
        this.password = password;
        this.databaseName = databaseName;
        this.url = url;
        this.port = port;
        this.params = params;
    }

    @Bean
    public DataSource getDataSource() {
        final DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(String.format(DATASOURCE_URL, url, port, databaseName, params));
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();
    }
}