package ru.yandex.wmconsole.viewer.api.servantlet.originals;

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.info.BriefHostInfo;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.error.ClientProblem;
import ru.yandex.wmconsole.viewer.api.ApiUrl;
import ru.yandex.wmconsole.viewer.originals.OriginalTextLimits;
import ru.yandex.wmconsole.viewer.originals.OriginalsResponse;

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

    private ApiUrl apiUrl;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId, BriefHostInfo briefHostInfo)
            throws ClientException {
        OriginalTextLimits limits = originalTextsService.getLimits(briefHostInfo);
        if (limits.getCurrentTextCount() >= limits.getMaxTextsCount()) {
            throw new ClientException(ClientProblem.ORIGINALS_LIMIT_EXCEEDED, "You exceeded limit on original texts added per day");
        }
        String originalText = getRequiredXmlParam(req, "/original-text/content");
        if (originalText.length() < limits.getMinTextLength()) {
            throw new ClientException(ClientProblem.ORIGINALS_TEXT_TOO_SHORT,
                    "Text too short. Minimum length is " + limits.getMinTextLength());
        }
        if (originalText.length() > limits.getMaxTextLength()) {
            throw new ClientException(ClientProblem.ORIGINALS_TEXT_TOO_LONG,
                    "Text too long. Maximum length is " + limits.getMaxTextLength());
        }

        OriginalsResponse originalsResponse;
        originalsResponse = originalTextsService.addText(briefHostInfo, originalText);

        ApiUrl.V2.Host host = apiUrl.v2().host(briefHostInfo.getId());
        if (originalsResponse.isCanAdd()) {
            if (!originalsResponse.getTexts().isEmpty()) {
                res.addData(new OriginalTextsReponse(originalsResponse, host, true));
            } else {
                log.error("Unable to save original texts, empty response: host=" + briefHostInfo.getId());
                throw new ClientException(ClientProblem.INTERNAL_ERROR, "Unable to save original text");
            }
        } else {
            throw new ClientException(ClientProblem.ORIGINALS_LIMIT_EXCEEDED, "You exceeded limit on original texts added per day");
        }
    }

    @Required
    public void setApiUrl(ApiUrl apiUrl) {
        this.apiUrl = apiUrl;
    }
}
