package ru.yandex.webmaster.common.health;

import com.codahale.metrics.health.HealthCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmconsole.data.partition.WMCPartition;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.service.JdbcConnectionWrapperService;

/**
 * @author aherman
 */
public class DbConnectedCheck extends HealthCheck {
    private static final Logger log = LoggerFactory.getLogger(DbConnectedCheck.class);

    public static final String VALIDATION_QUERY = "SELECT 1";

    private JdbcConnectionWrapperService readJdbcConnectionWrapperService;
    private JdbcConnectionWrapperService writeJdbcConnectionWrapperService;

    @Override
    protected Result check() throws Exception {
        log.debug("Try to check db");
        checkDb(writeJdbcConnectionWrapperService);
        checkDb(readJdbcConnectionWrapperService);
        log.debug("Db check finished");
        return Result.healthy("All db shards is connected");
    }

    private void checkDb(JdbcConnectionWrapperService jdbcConnectionWrapperService) throws InternalException {
        for (int i = 0; i < writeJdbcConnectionWrapperService.getDatabaseCount(); i++) {
            jdbcConnectionWrapperService.getJdbcTemplate(new WMCPartition(i)).queryForInt(VALIDATION_QUERY);
        }
    }

    @Required
    public void setReadJdbcConnectionWrapperService(JdbcConnectionWrapperService readJdbcConnectionWrapperService) {
        this.readJdbcConnectionWrapperService = readJdbcConnectionWrapperService;
    }

    @Required
    public void setWriteJdbcConnectionWrapperService(JdbcConnectionWrapperService writeJdbcConnectionWrapperService) {
        this.writeJdbcConnectionWrapperService = writeJdbcConnectionWrapperService;
    }
}
