package ru.yandex.webmaster3.viewer.http.originaltext;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.storage.originaltext.OriginalText;
import ru.yandex.webmaster3.storage.originaltext.OriginalTextLimits;
import ru.yandex.webmaster3.storage.originaltext.OriginalTextService;
import ru.yandex.webmaster3.storage.originaltext.OriginalsResponse;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

/**
 * @author aherman
 */
@WriteAction
@Category("originaltext")
public class AddOriginalTextAction extends AbstractUserVerifiedHostAction<AddOriginalTextRequest, AddOriginalTextResponse> {
    private OriginalTextService originalTextService;

    @Override
    public AddOriginalTextResponse process(AddOriginalTextRequest request) {
        OriginalTextLimits limits = originalTextService.getLimits(request.getHostId());
        if (limits.getTextQuotaUsed() >= limits.getTextQuota()) {
            return new AddOriginalTextResponse.QuotaExceededError(limits.getTextQuota());
        }
        String text = StringUtils.trimToEmpty(request.getText());
        if (text.length() < limits.getMinTextLength()) {
            return new AddOriginalTextResponse.TextTooShortError();
        } else if (text.length() > limits.getMaxTextLength()) {
            return new AddOriginalTextResponse.TextTooLongError();
        }
        OriginalsResponse originalsResponse = originalTextService.addText(request.getHostId(), text);
        if (originalsResponse.getError() == OriginalsResponse.OriginalsError.TEXT_ALREADY_ADDED) {
            return new AddOriginalTextResponse.TextAlreadyAddedError();
        }
        if (!originalsResponse.isCanAdd().orElse(true)) {
            return new AddOriginalTextResponse.QuotaExceededError(limits.getTextQuota());
        }
        List<OriginalText> texts = originalsResponse.getTexts();
        if (text.isEmpty()) {
            throw new WebmasterException("Empty response from Originals service",
                    new WebmasterErrorResponse.OriginalsErrorResponse(this.getClass(), 0));
        }
        return new AddOriginalTextResponse.NormalResponse(texts.get(0));
    }

    @Required
    public void setOriginalTextService(OriginalTextService originalTextService) {
        this.originalTextService = originalTextService;
    }
}
