package ru.yandex.wmconsole.service;

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.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.InternalProblem;
import ru.yandex.wmtools.common.service.AbstractExternalHttpService;

/**
 * @author avhaliullin
 */
public class SendInternalNotificationService extends AbstractExternalHttpService {
    private static final Logger log = LoggerFactory.getLogger(SendInternalNotificationService.class);

    private int socketTimeoutMillis = 15000;
    private int connectionRetryCount = 1;

    private void sendWithRetry(String urlAddress, Map<String, Object> params, int socketTimeout) throws InternalException {
        InternalException problem = null;
        for (int i = 0; i < connectionRetryCount + 1; i++) {
            try {
                if (i > 0) {
                    log.debug("Retry");
                }
                httpPostResponse(urlAddress, params, socketTimeout);
            } catch (InternalException e) {
                problem = e;
                log.debug("Failed to do httpPost.", e);
                continue;
            }
            log.debug("Succeeded internal notify.");
            return;
        }
        throw new InternalException(InternalProblem.CONNECTION_PROBLEM, "Failed to send with retry", problem);
    }

    public void sendInternalNotification(NotificationTypeEnum type, Map<String, Object> params) throws InternalException {
        log.debug("Sending internal notification to " + externalServantUrl);

        params.put("type", type.getValue());
        params.put("mode", "prod");

        sendWithRetry("internalNotify", params, socketTimeoutMillis);
    }

    @Required
    public void setSocketTimeoutMillis(int socketTimeoutMillis) {
        this.socketTimeoutMillis = socketTimeoutMillis;
    }

    @Required
    public void setConnectionRetryCount(int connectionRetryCount) {
        this.connectionRetryCount = connectionRetryCount;
    }
}
