package ru.yandex.wmconsole.servantlet;

import java.net.URL;

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

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.data.AddUrlRequest;
import ru.yandex.wmconsole.service.AddUrlService;
import ru.yandex.wmconsole.service.error.WMCUserProblem;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;
import ru.yandex.wmtools.common.servantlet.AbstractServantlet;

/**
 * Encodes url using punycode and performs some checks.
 *
 * @author ailyin
 */
public class AddUrlServantlet extends AbstractServantlet {
    private static final Logger log = LoggerFactory.getLogger(AddUrlServantlet.class);

    static final String PARAM_URL = "url";

    // Not error here - same error in verstka
    static final String PARAM_REMORE_IP="_remore_ip";
    static final String PARAM_REMOTE_IP="_remote_ip";
    static final String PARAM_YANDEX_UID = "_yandexuid";

    private AddUrlService addUrlService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res) throws UserException, InternalException {
        log.debug("AddUrl: Started");

        String urlParam = getRequiredStringParam(req, PARAM_URL);

        String userIp = getStringParam(req, PARAM_REMORE_IP);
        if (userIp == null) {
            userIp = getStringParam(req, PARAM_REMOTE_IP);
        }
        String yandexUid = getStringParam(req, PARAM_YANDEX_UID);

        final URL url = prepareUrl(urlParam, true);
        if (!tryConvertURLtoURI(url)) {
            throw new UserException(UserProblem.INVALID_URL, "Can't convert URL to URI Invalid url: " + url);
        }
        AddUrlRequest addUrlRequest = new AddUrlRequest(url, req.getRemoteIp(), req.getUserId(), userIp, yandexUid);
        try {
            addUrlService.addUrl(addUrlRequest, true, getYaDomainParam(req), false);
        } catch (UserException e) {
            // WMCON-6063 ignore addurl quota error silently
            if (e.getProblem() == WMCUserProblem.ADD_URL_RATE_LIMIT) {
                log.warn("Ignore quota error silently");
            } else {
                throw e;
            }
        }
        log.debug("AddUrl: Finished");
    }

    @Required
    public void setAddUrlService(AddUrlService addUrlService) {
        this.addUrlService = addUrlService;
    }
}
