package ru.yandex.webmaster.common.health;

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

import ru.yandex.wmconsole.service.DispatcherHttpService;
import ru.yandex.wmtools.common.error.InternalException;

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

    private DispatcherHttpService dispatcherHttpService;

    @Override
    protected Result check() throws Exception {
        String yandexRuMainMirror;
        try {
            yandexRuMainMirror = dispatcherHttpService.getMainMirror("yandex.ru", "DispatcherHealthCheck");
        } catch (InternalException e) {
            log.error("Unable to get main mirror for yandex.ru", e);
            return Result.unhealthy("Unable to get main mirror for yandex.ru: %s", e.getMessage());
        }

        if (StringUtils.isEmpty(yandexRuMainMirror)) {
            log.error("Empty main mirror for yandex.ru");
            return Result.unhealthy("Empty main mirror for yandex.ru");
        }

        return Result.healthy("Main mirror for yandex.ru: %s", yandexRuMainMirror);
    }

    @Required
    public void setDispatcherHttpService(DispatcherHttpService dispatcherHttpService) {
        this.dispatcherHttpService = dispatcherHttpService;
    }
}
