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.HostRobotDbInfo;
import ru.yandex.wmconsole.data.info.HostDbHostInfo;
import ru.yandex.wmconsole.service.HostDbHostInfoService;
import ru.yandex.wmconsole.service.dao.TblRobotdbInfoDao;

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

    private TblRobotdbInfoDao tblRobotdbInfoDao;
    private HostDbHostInfoService hostDbHostInfoService;

    private String checkHostname;

    @Override
    protected Result check() throws Exception {
        log.debug("Check robot_db_info for host: {}", checkHostname);
        HostDbHostInfo hostDbHostInfo = hostDbHostInfoService.getHostDbHostInfo(checkHostname);
        HostRobotDbInfo robotDbInfo = tblRobotdbInfoDao.getRobotDbInfo(hostDbHostInfo);
        log.debug("robot_db_info for host[{}]: index_count={}, links_count={}", checkHostname,
                robotDbInfo.getIndexCount(), robotDbInfo.getLinksCount());
        if (robotDbInfo.getIndexCount() != null && robotDbInfo.getIndexCount() > 0 &&
                robotDbInfo.getLinksCount() != null && robotDbInfo.getLinksCount() > 0) {
            return Result.healthy("robot_db_info for host[%s]: index_count=%d, links_count=%d",
                    checkHostname, robotDbInfo.getIndexCount(), robotDbInfo.getLinksCount());
        } else {
            return Result.unhealthy(
                    "Some information is missing in robot_db_info for host[%s]: index_count=%s, links_count=%s",
                    checkHostname, String.valueOf(robotDbInfo.getIndexCount()),
                    String.valueOf(robotDbInfo.getLinksCount()));
        }
    }

    @Required
    public void setTblRobotdbInfoDao(TblRobotdbInfoDao tblRobotdbInfoDao) {
        this.tblRobotdbInfoDao = tblRobotdbInfoDao;
    }

    @Required
    public void setHostDbHostInfoService(HostDbHostInfoService hostDbHostInfoService) {
        this.hostDbHostInfoService = hostDbHostInfoService;
    }

    @Required
    public void setCheckHostname(String checkHostname) {
        this.checkHostname = checkHostname;
    }
}
