package ru.yandex.wmconsole.notifier.handler;

import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmconsole.data.NotificationTypeEnum;
import ru.yandex.wmconsole.service.CollectConcurrencyService;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class ErrorsGrowNotificationHandler implements Handler {
    private static final Logger log = LoggerFactory.getLogger(ErrorsGrowNotificationHandler.class);

    private static final double MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;

    private CollectConcurrencyService collectConcurrencyService;
    private SearchUpdateNotificationHandler searchUpdateNotificationHandler;

    @Override
    public void handleNotification(String xmlData) {
        try {
            Date lastUpdate = collectConcurrencyService.getTypeUpdateDate(NotificationTypeEnum.ERRORS_GROW);
            Date now = new Date();
            if (((double) now.getTime() - (double) lastUpdate.getTime()) / MILLISECONDS_PER_DAY > 1.0) {
                log.debug("Robot update happened");
                collectConcurrencyService.updateType(NotificationTypeEnum.ERRORS_GROW);
                searchUpdateNotificationHandler.internalHandleNotification();
            } else {
                log.warn("Errors grow and search update appear to happen too early");
            }
        } catch (InternalException e) {
            log.error("InternalException in " + getClass().getName() + " while updating concurrency table for errors grow", e);
        }
    }

    @Override
    public void internalHandle(String... params) {
        throw new UnsupportedOperationException("Internal handle not supported for ErrorsGrow notification");
    }

    @Override
    public void handleInternalNotification(Map<String, String> params) {
        throw new UnsupportedOperationException("Internal handle not supported for ErrorsGrow notification");
    }

    @Required
    public void setCollectConcurrencyService(CollectConcurrencyService collectConcurrencyService) {
        this.collectConcurrencyService = collectConcurrencyService;
    }

    @Required
    public void setSearchUpdateNotificationHandler(SearchUpdateNotificationHandler searchUpdateNotificationHandler) {
        this.searchUpdateNotificationHandler = searchUpdateNotificationHandler;
    }
}
