package com.lanyuanxiaoyao.service.check.actions;

import com.lanyuanxiaoyao.service.check.configuration.MysqlConfigurationProperties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

/**
 * @author lanyuanxiaoyao
 * @date 2024-02-22
 */
@Component
@ConditionalOnBean(MysqlConfigurationProperties.class)
public class MysqlChecker extends Checker {
    private static final Logger logger = LoggerFactory.getLogger(MysqlChecker.class);

    private final MysqlConfigurationProperties mysqlConfigurationProperties;

    public MysqlChecker(MysqlConfigurationProperties mysqlConfigurationProperties) {this.mysqlConfigurationProperties = mysqlConfigurationProperties;}

    @Override
    public void check() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        for (MysqlConfigurationProperties.MysqlInfo target : mysqlConfigurationProperties.getTargets()) {
            try (Connection connection = DriverManager.getConnection(target.getUrl(), target.getUsername(), target.getPassword())) {
                if (connection.isClosed()) {
                    logger.warn("Database connect failure {}", target.getUrl());
                    continue;
                }
                try (Statement statement = connection.createStatement()) {
                    try (ResultSet resultSet = statement.executeQuery("select version()")) {
                        if (resultSet.next()) {
                            logger.info("Database version {}", resultSet.getString(1));
                        }
                    }
                }
            }
        }
    }

    @Override
    public String description() {
        return "Check mysql";
    }
}
