package com.usthe.collector.common.cache.support;

import com.usthe.collector.common.cache.CacheCloseable;
import com.usthe.collector.common.cache.CacheDetectable;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;

/**
 * @author tomsun28
 * @date 2021/9/1 21:24
 */
@Slf4j
public class CommonJdbcConnect implements CacheCloseable, CacheDetectable {

    private Connection connection;

    public CommonJdbcConnect(Connection connection) {
        this.connection = connection;
    }

    @Override
    public void close() {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            log.error("close jdbc connect error: {}", e.getMessage());
        }
    }

    @Override
    public boolean available() {
        if (connection == null) {
            return false;
        }
        try {
            return !connection.isClosed();
        } catch (Exception e) {
            log.error("detect jdbc connect error: {}", e.getMessage());
            return false;
        }
    }

    @Override
    protected void finalize() throws Throwable {
        close();
        super.finalize();
    }

    public Connection getConnection() {
        return connection;
    }
}
